using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using MBLocale;

/// <summary>
/// Summary description for DisplayGrid
/// </summary>
public class GenerateGrid
{
    HDDatabase HDD;
    security HDS;
    DynamicDisplayI DDI = new DynamicDisplayI();
    string sUTC_Offset = "";
    public ArrayList currencyCode_Rate = new ArrayList();
    DataTable dtaPageSrch;
    //    DataRow drMenuRights = null;
    //    DataRow drObjectRights = null;
    public GenerateGrid()
    {
        //
        // TODO: Add constructor logic here
    }

    public void loadCurrencySettings()
    {
        ArrayList cols = new ArrayList();
        cols.Add("c_rate");
        cols.Add("c_code");
        currencyCode_Rate = DDI.getUserSetting("sy_usr", "currency_id", "sy_currency", cols, "c_code");
        currencyCode_Rate.Add(DDI.getCorporateCurrency());
    }
    //public bool DisplayPage(String strPagesetRowId, HtmlForm frmObj)
    //{
    //    return DisplayPage(strPagesetRowId, frmObj, "");
    //}

    private DataSet sortData(DataSet dsInp, string colName)
    {
        DataSet dsRet = new DataSet();
        foreach (DataTable dt in dsInp.Tables)
        {
            if (dt.Columns.Contains(colName))
            {
                DataView dv = dt.DefaultView;
                dv.Sort = colName + " desc";
                DataTable dtNew = dv.Table.Clone();
                foreach (DataRowView drv in dv)
                    dtNew.Rows.Add(drv);
                dsRet.Tables.Add(dtNew);
            }
            else
                dsRet.Tables.Add(dt.Copy());
        }
        return dsRet;
    }

    private void fillMasterValues(ref DataSet dsData, ref DataTable dtMaster, string StoredField, string DisplayField, string AssignToField)
    {
        foreach (DataRow dr in dsData.Tables[0].Rows)
        {
            DataRow[] drr = dtMaster.Select("af_row_id='" + dr[AssignToField].ToString() + "'");
            if (drr.Length > 0)
                dr[AssignToField] = drr[0][DisplayField];
            else
                dr[AssignToField] = "Master record not available";
        }
    }

    public void populateMasterFieldValues(ref DataSet dsData, ref DataTable dtSrchInfo, ref DataTable dtPageKeys)
    {
        foreach (DataRow dr in dtPageKeys.Rows)
        {
            DataRow[] drr = dtSrchInfo.Select("search_attrib_id='" + dr["attrib_id"].ToString() + "'");

            if (drr.Length > 0)
            {
                for (int iRowCount = 0; iRowCount < drr.Length; iRowCount++)
                {
                    HDD = new HDDatabase();
                    DataTable dtMaster = HDD.GetDataTable("select * from " + HDD.GetColumnValue("select object_table from sy_obj where object_id='" + dr["master_obj"].ToString() + "'") + "");
                    fillMasterValues(ref dsData, ref dtMaster, dr["attrib_id"].ToString(), dr["display_att"].ToString(), drr[iRowCount]["search_attrib_name"].ToString());
                }
            }
        }
    }

    public string getUserDisplayName()
    {
        HDD = new HDDatabase();
        string userDisplayField = HDD.GetColumnValue("sy_acr_mem", "mem_id", "af_row_id='30583eb791cb7d5b'");
        userDisplayField = userDisplayField.Trim().Length == 0 ? "user_id" : userDisplayField;
        return userDisplayField;
    }

    public bool DisplayPage(String strPagesetRowId, HtmlForm frmObj)
    {
        HDD = new HDDatabase();
        HDS = new security();
        bool bRead = false;
        bool bCreate = false;
        bool bEdit = false;
        bool bDelete = false;
        HDS.getPagesetRights(strPagesetRowId, ref bRead, ref bCreate, ref bEdit, ref bDelete);
        sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
        loadCurrencySettings();

        bool blnStatus = true;
        if (bRead)
        {
            PageInfoLoad PIL = new PageInfoLoad();
            DataSet dsePageObj = PIL.GetPageSetPagesSrchInfo(strPagesetRowId);
            DataTable dtaPageSet = dsePageObj.Tables["PageSet"];
            DataTable dtaPage = dsePageObj.Tables["Page"];
            DataTable dtaPageKeys = dsePageObj.Tables["PageKeys"];
            DataTable dtaPageSrch = dsePageObj.Tables["PageSrch"];
            DataTable dtaPageControls = dsePageObj.Tables["Page Controls"];

            string sNoofRecords = this.HDD.getAcrMemValue("3813ac7202378893", "1"); // added by Jeya Prabha on 17-Sep-2007 to set the number of records displayed
            if (sNoofRecords != "" && sNoofRecords != "0")
                GlobalValues.intNoOfRecordsPerPage = int.Parse(sNoofRecords);
            else
                GlobalValues.intNoOfRecordsPerPage = 8;

            //drMenuRights = HDD.getMenuRightsForUser();
            //added for quick search

            if (HttpContext.Current.Request["PK"] == null)
            {
                BuildQuickSearch(dtaPage, dtaPageSrch, strPagesetRowId, frmObj);
            }

            Hashtable hsDatatype = new Hashtable();
            string strSql = PageSetSelectSql(dtaPage, dtaPageKeys, dtaPageSrch, ref dtaPageControls, ref hsDatatype, "");
            if (strSql != "")
            {
                if (frmObj.Page.IsPostBack)
                    strSql += PagesetQuickSearchSql(dtaPageSrch, frmObj);
                strSql += HDS.GridRowLevelSecuritySql(dtaPage);
                DataSet dseObj = new DataSet();
                if (dtaPage.Rows[0]["page_table_name"].ToString() == "sy_notes") // Added by 'Imran Gani' on 25-May-2012, to sort grid list of notes with notes date.
                {
                    strSql = strSql.TrimEnd() + " order by [" + dtaPage.Rows[0]["page_id"].ToString() + "].[notes_date] desc";
                    dseObj = HDD.GetDataset(strSql);
                }
                else
                {
                    string strModifiedFields = GetModifiedFields(ref dtaPage, ref dtaPageControls);
                    if (strModifiedFields != "")
                        strSql = strSql.TrimEnd() + " order by " + strModifiedFields;
                    dseObj = HDD.GetDataset(strSql, true);
                }
                //DataSet dseObj = HDD.GetDataset(strSql, true); Commanded by 'Imran Gani' on 25-May-2012, for above if statement.
                //DataTable dt = dseObj.Tables[0];
                //SortDataTable(ref dt);

                if (dseObj.Tables.Count == 0)
                {
                    return false;
                }
                else
                {
                    for (int i = 0; i < dtaPage.Rows.Count; i++) //added by Prithi on 13 Oct 2008 to display the display field instead of storage field in place of af_row_id.
                    {
                        string strPageId, strSearchAttribName, strBindRowID;
                        strPageId = dtaPage.Rows[i]["page_id"].ToString();
                        DataRow[] droPageSrch = dtaPageSrch.Select("page_id='" + strPageId.Replace("'", "''") + "' and list_flag=1", "search_seq");
                        for (int j = 0; j < droPageSrch.Length; j++)
                        {
                            strSearchAttribName = droPageSrch[j]["search_attrib_name"].ToString();
                            if (strSearchAttribName == "")
                            {
                                strSearchAttribName = droPageSrch[j]["search_attrib_id"].ToString();
                            }

                            if (droPageSrch[j]["search_attrib_id"].ToString() == "created_by" || droPageSrch[j]["search_attrib_id"].ToString() == "modified_by" || droPageSrch[j]["search_attrib_id"].ToString() == "owner_id") // Added by srivatsan on June 15 2009 for owner id field
                            {
                                string sUserDisplayName = getUserDisplayName();
                                DataTable dtUser = HDD.GetDataTable("select *, " + sUserDisplayName + " as display_name from sy_usr");
                                string sUser_afrowid = "";
                                string sUser = "";
                                foreach (DataRow dr in dseObj.Tables[0].Rows)
                                {
                                    if (sUser_afrowid != dr[strSearchAttribName].ToString())
                                    {
                                        sUser_afrowid = dr[strSearchAttribName].ToString();
                                        DataRow[] drr = dtUser.Select("af_row_id='" + sUser_afrowid + "'");
                                        if (drr.Length > 0)
                                            sUser = drr[0]["display_name"].ToString();//sUser = drr[0]["user_id"].ToString();
                                        drr = null;
                                    }
                                    dr[strSearchAttribName] = sUser;
                                }
                                dtUser.Dispose();
                                dtUser = null;
                            }

                            strBindRowID = droPageSrch[j]["control_bind_id"].ToString();
                            if (strBindRowID != "")
                            {
                                string search_attrib_name = droPageSrch[j]["search_attrib_name"].ToString();
                                string sBindStoreField = "", sBindDisplayField = "", sBindTable = "";
                                DataRow drBind = null;
                                if (strBindRowID != "")
                                    drBind = HDD.GetTableRow("select * from sy_bnd where af_row_id = '" + strBindRowID + "';");
                                if (drBind != null)
                                {
                                    sBindStoreField = drBind["bind_value"].ToString();
                                    sBindDisplayField = drBind["bind_text"].ToString();
                                    sBindTable = drBind["bind_table"].ToString();
                                    //if (sBindStoreField.ToLower() == "af_row_id")  // Commented by srivatsan on July 15 2009
                                    //{
                                    //    string sSql = "";
                                    //    DataTable dt = new DataTable();
                                    //    sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable + "";
                                    //    dt = HDD.GetDataTable(sSql, sBindTable);
                                    //    foreach (DataRow dr in dseObj.Tables[0].Rows)
                                    //    {
                                    //        if (dr[strSearchAttribName].ToString() == "") dr[strSearchAttribName] = "";
                                    //        else
                                    //        {
                                    //            DataRow[] drr = dt.Select("af_row_id= '" + dr[strSearchAttribName].ToString() + "'");
                                    //            if (drr.Length == 0) dr[strSearchAttribName] = "Record Not Found";
                                    //            else
                                    //            {
                                    //                for (int l = 0; l < drr.Length; l++)
                                    //                {
                                    //                    dr[strSearchAttribName] = drr[l][sBindDisplayField].ToString();
                                    //                }
                                    //            }
                                    //        }
                                    //    }
                                    //    dt.Dispose();
                                    //    dt = null;
                                    //}


                                    // Modified by srivatsan on july 15 2009
                                    addBindColumn(dseObj, search_attrib_name);

                                    string af_row_ids = "";
                                    if (dseObj != null)
                                    {
                                        if (dseObj.Tables.Count > 0)
                                        {
                                            if (dseObj.Tables[0].Rows.Count > 0)
                                            {
                                                if (search_attrib_name != "")
                                                {
                                                    af_row_ids = getDistinct(dseObj.Tables[0], search_attrib_name);
                                                }
                                                else
                                                {
                                                    af_row_ids = getDistinct(dseObj.Tables[0], droPageSrch[j]["search_attrib_id"].ToString());
                                                }
                                            }
                                        }
                                    }
                                    string sSql = "";
                                    DataTable dt = new DataTable();
                                    sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable + " where " + sBindStoreField + " in (" + af_row_ids + ")";
                                    dt = HDD.GetDataTable(sSql, sBindTable);
                                    foreach (DataRow dr in dseObj.Tables[0].Rows)
                                    {
                                        if (dr[strSearchAttribName].ToString() == "")
                                            dr[strSearchAttribName] = "";
                                        else
                                        {
                                            // DataRow[] drr = dt.Select(""+sBindStoreField+"= '" + dr[strSearchAttribName].ToString() + "'");

                                            DataRow[] drr = null;
                                            try
                                            {
                                                drr = dt.Select("" + sBindStoreField + "= '" + dr[strSearchAttribName].ToString() + "'");
                                            }
                                            catch
                                            {
                                                drr = dt.Select("" + dt.Columns[1].ToString() + "= '" + dr[strSearchAttribName].ToString() + "'");
                                            }
                                            if (drr.Length == 0)
                                                dr[strSearchAttribName] = "Record Not Found";
                                            else
                                            {
                                                for (int l = 0; l < drr.Length; l++)
                                                {
                                                    if (!sBindDisplayField.Contains("+"))
                                                    {
                                                        dr[strSearchAttribName] = drr[l][sBindDisplayField].ToString();
                                                    }
                                                    else
                                                    {
                                                        try
                                                        {
                                                            dr[strSearchAttribName] = drr[l]["Column1"].ToString();
                                                        }
                                                        catch
                                                        {
                                                            dr[strSearchAttribName] = "";
                                                        }

                                                    }
                                                }
                                            }
                                        }
                                    }
                                    dt.Dispose();
                                    dt = null;

                                }
                            }
                        }
                    }

                    dseObj.Tables[0].TableName = dtaPage.Rows[0]["page_id"].ToString();
                    sortData(ref dseObj);
                    if (dtaPageKeys.Rows.Count > 0)
                        populateMasterFieldValues(ref dseObj, ref dtaPageSrch, ref dtaPageKeys);
                    //dseObj = sortData(dseObj, "modified_at");

                    BuildGrid(dseObj, strPagesetRowId, frmObj, bCreate, bEdit, bDelete, ref dsePageObj, ref hsDatatype);
                }
            }
            HDS.displayHelp(dtaPage, DDI.FindControl(frmObj.Controls, "imgHelp"));


            if ((HttpContext.Current.Request.QueryString["PK"] == null) && (HDS.allRightsForNGMODEL() == false))
            {
                showadditionalsections(strPagesetRowId, ref frmObj, dsePageObj);
            }

        }



        HtmlInputButton btnObj = (HtmlInputButton)DDI.FindControl(frmObj.Controls, "btnAddNew");  // Modified by srivatsan
        if (btnObj != null)
            if (bCreate.ToString() == false.ToString())
                makeAddButtonInvisible(frmObj, btnObj);
        if (btnObj != null)
            if (!HDS.getRightsForPagesetObjects(strPagesetRowId, "create", true))
                makeAddButtonInvisible(frmObj, btnObj);

        return blnStatus;
    }
    private string getColName(string content)
    {
        try
        {
            string colName = "";
            colName = content.Substring(content.IndexOf("].[") + 3);
            colName = colName.Substring(0, colName.IndexOf("]"));
            return colName;
        }
        catch (Exception e)
        {
            return "";
        }
    }
    private string getTableName(string content)
    {
        try
        {
            string tableName = "";
            tableName = content.Substring(0, content.IndexOf("].["));
            tableName = tableName.Trim('[').Trim(']');
            return tableName;
        }
        catch (Exception e)
        {
            return "";
        }
    }
    public void sortData(ref DataSet dseObj)
    {
        try
        {
            if (HttpContext.Current.Session["datasort"] == null)
                return;
            string datasort = HttpContext.Current.Session["datasort"].ToString();
            if (datasort.Trim() == "")
                return;
            string[] array = datasort.Split(' ');
            string content = "";
            string colName = "";
            string tableName = "";
            //for (int i = 0; i < array.Length-1; i++)
            //    content = content + " " + array[i];
            //content = content.TrimStart(' ');
            content = datasort;

            tableName = getTableName(content);
            colName = getColName(content);

            datasort = content.Substring(content.IndexOf("].[") + 3).Replace("]", "");

            ArrayList tables = new ArrayList();
            foreach (DataTable dt in dseObj.Tables)
            {
                if (tableName != dt.TableName)
                    continue;
                if (!dt.Columns.Contains(colName))
                    continue;
                tables.Add(dt.TableName);
            }
            for (int j = 0; j < tables.Count; j++)
            {
                DataTable dt = dseObj.Tables[tables[j].ToString()];
                DataTable dtNew = dt.Clone();
                DataRow[] drs = dt.Select("", datasort);
                foreach (DataRow dr in drs)
                    dtNew.ImportRow(dr);
                dt = dtNew;
                dseObj.Tables.Remove(tables[j].ToString());
                dseObj.Tables.Add(dtNew);
                dseObj.AcceptChanges();
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in sortData function. Error " + e.Message);
        }
    }
    /// <summary>
    /// Sorts the datatable based on the modified date/modified_at
    /// </summary>
    /// <param name="dt"></param>
    private void SortDataTable(ref DataTable dt)
    {
        string sort = "";
        if (dt.Columns.Contains("modified_date"))
            sort = "modified_date";
        else if (dt.Columns.Contains("modified_at"))
            sort = "modified_at";
        if (sort == "")
            return;
        DataTable newDT = dt.Clone();
        int rowCount = dt.Rows.Count;

        DataRow[] foundRows = dt.Select(null, sort + " desc"); // Sort with Column name 
        for (int i = 0; i < rowCount; i++)
        {
            object[] arr = new object[dt.Columns.Count];
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                arr[j] = foundRows[i][j];
            }
            DataRow data_row = newDT.NewRow();
            data_row.ItemArray = arr;
            newDT.Rows.Add(data_row);
        }

        //clear the incoming dt 
        dt.Rows.Clear();

        for (int i = 0; i < newDT.Rows.Count; i++)
        {
            object[] arr = new object[dt.Columns.Count];
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                arr[j] = newDT.Rows[i][j];
            }

            DataRow data_row = dt.NewRow();
            data_row.ItemArray = arr;
            dt.Rows.Add(data_row);
        }
        newDT = null;
    }
    public void makeAddButtonInvisible(HtmlForm frmObj, HtmlInputButton btnObj)  // Modified by srivatsan on June 23 2009
    {
        btnObj.Visible = false;
        HtmlInputButton hb = (HtmlInputButton)DDI.FindControl(frmObj.Controls, "btnAddNewTop");
        if (hb != null)
        {
            hb.Visible = false;
        }
        //HtmlTableCell htRow = (HtmlTableCell)DDI.FindControl(frmObj.Controls, "tdAddButton");
        //htRow.Visible = false;
        //htRow.Height = "0";
        //htRow.ColSpan = -1;
        //htRow.RowSpan = -1;
    }

    protected string btnAdd_URL(string strPagesetRowId)
    {
        string strMenuRowId = HttpContext.Current.Request.QueryString["mn"].ToString();
        //added for static page list view AddNew
        string sEditPage = "DynamicScreen.aspx";
        HDDatabase HDD = new HDDatabase();
        GenerateGrid objGD = new GenerateGrid();
        sEditPage = objGD.getEditPage(HDD, strMenuRowId);
        string PK = "";// HttpContext.Current.Request.QueryString["PK"].ToString();
        string strPageUrl = sEditPage + "?pgs_id=" + strPagesetRowId + "&mn=" + strMenuRowId;
        if (PK != "")
            strPageUrl = strPageUrl + "&PK=" + PK;
        strPageUrl = addMasterPrimaryKey(strPageUrl);
        return strPageUrl;
    }

    private HtmlInputButton /*Button*/ getAddNewButton(string strPagesetRowId, string append2Id)
    {
        //Button btnAdd = new Button();
        //btnAdd.Text = "Add New";
        //btnAdd.ID = strPagesetRowId + append2Id;//addded by sanal on 25 Apr 2008
        //btnAdd.Attributes.Add("Pageset", strPagesetRowId);

        ////btnAdd.Attributes.Add("OnClick", "javascript:disableThisNoValidation('ctl00_ContentPlaceHolder3_" + strPagesetRowId + "','Loading...'); window.location.href('"+getAddNewLink(btnAdd)+"');");//addded by sanal on 25 Apr 2008
        ////btnAdd.Click += new EventHandler(btnAdd_Click);

        HtmlInputButton btnAdd = new HtmlInputButton();
        btnAdd.Value = "Add New";
        btnAdd.Attributes.Add("Pageset", strPagesetRowId);
        if (strPagesetRowId == "5f4649e689509dea") // Added by 'Imran Gani' on Sep 18 2012 for Documents changes
            btnAdd.Attributes.Add("onclick", "javascript:disableThisNoValidation('ctl00_ContentPlaceHolder3_" + strPagesetRowId + "','Loading...'); window.location.href=('" + getLinkForDocument(btnAdd) + "');");
        else
            btnAdd.Attributes.Add("onclick", "javascript:disableThisNoValidation('ctl00_ContentPlaceHolder3_" + strPagesetRowId + "','Loading...'); window.location.href=('" + getAddNewLink(btnAdd) + "');");
        btnAdd.ID = strPagesetRowId + append2Id;


        //        btnAdd.OnClientClick = "javascript:disableThisNoValidation('ctl00_ContentPlaceHolder3_" + strPagesetRowId + "','Loading...'); window.location.href=('" + getAddNewLink(btnAdd) + "');"; 


        //btnAdd.UseSubmitBehavior = false;//addded by sanal on 25 Apr 2008
        //btnAdd.CausesValidation = false ;
        return btnAdd;
    }

    ////private void addHeaderForChildGrids(ref HtmlTable hta, string Pageset_Id, bool Create, bool Edit, bool Delete, int colCount)
    ////{
    ////    HtmlTable htTable = new HtmlTable();
    ////    HtmlTableRow htr = new HtmlTableRow();
    ////    HtmlTableCell htc = new HtmlTableCell();
    ////    Label lblHeading = new Label();
    ////    htTable.CellSpacing = 0;
    ////    htTable.CellPadding = 0;
    ////    htTable.Border = 1;

    ////    string strPageSetHeading = HDD.GetColumnValue("sy_pgs", "pageset_name", "pageset_id='" + Pageset_Id.Replace("'", "''") + "'");
    ////    lblHeading.Text = "&nbsp;" + GetPageIcons(Pageset_Id.Replace("'", "''")).Text + "&nbsp;" + strPageSetHeading + "&nbsp;"; // Modified by srivatsan
    ////    //lblHeading.ID = "lblHeading";
    ////    htc.Controls.Add(lblHeading);
    ////    htr.Cells.Add(htc);
    ////    htr.Attributes.Add("class", "grid_header_light");
    ////    htTable.Rows.Add(htr);

    ////    htc = new HtmlTableCell();
    ////    htr = new HtmlTableRow();
    ////    if (Create)
    ////        htc.Controls.Add(getAddNewButton(Pageset_Id, "Top"));

    ////    if (Pageset_Id.Trim().ToLower() == "ps_notes") // Added by srivatsan for View All Notes feature in notes section
    ////    {
    ////        HtmlInputButton btnviewnotes = new HtmlInputButton();
    ////        btnviewnotes.Attributes.Add("onclick", "javascript:window.location.href='viewAllNotes.aspx?PK=" + HttpContext.Current.Request.QueryString["PK"] + "&mn=" + HttpContext.Current.Request.QueryString["mn"] + "'");
    ////        btnviewnotes.ID = "btn_viewall_notes_top";
    ////        btnviewnotes.Value = "View All";
    ////        htc.Controls.Add(btnviewnotes);
    ////    }

    ////    htc.Height = "15px";
    ////    htc.VAlign = "middle";
    ////    int iColSpan = colCount - 1;
    ////    //if (Create) iColSpan++;
    ////    //if (Edit) iColSpan++;
    ////    //if (Delete) iColSpan++;
    ////    iColSpan++;//if (Create || Edit || Delete) 

    ////    htr.Cells.Add(htc);
    ////    //htr.Attributes.Add("class", "grid_header_light");
    ////    htTable.Rows.Add(htr);
    ////    htTable.Width = "100%";
    ////    htTable.Border = 0;
    ////    HtmlTableRow htRow1 = new HtmlTableRow();
    ////    HtmlTableRow htRow = new HtmlTableRow();
    ////    HtmlTableCell htCell = new HtmlTableCell();
    ////    HtmlTableCell htCell1 = new HtmlTableCell();
    ////    htCell.Controls.Add(htTable);
    ////    htCell.ColSpan = iColSpan;
    ////    htRow.Cells.Add(htCell);

    ////    //HtmlTableRow htrAdd = new HtmlTableRow();
    ////    //HtmlTableCell htcAdd = new HtmlTableCell();
    ////    //htcAdd.Controls.Add(btnAdd);
    ////    //htrAdd.Cells.Add(htcAdd);
    ////    //htTable.Rows.Add(htrAdd);

    ////    htCell1.Height = "25px";
    ////    htRow1.Cells.Add(htCell1);
    ////    hta.Controls.Add(htRow1);
    ////    hta.Controls.Add(htRow);
    ////}


    private void addHeaderForChildGrids(ref HtmlTable hta, string strPagesetRowId, bool Create, bool Edit, bool Delete, int colCount,int rowcount)
    {
        HtmlTable htTable = new HtmlTable();
        HtmlTableRow htr = new HtmlTableRow();
        HtmlTableCell htc = new HtmlTableCell();
        Label lblHeading = new Label();
        htTable.CellSpacing = 0;
        htTable.CellPadding = 0;
        htTable.Border = 1;

        //string strPageSetHeading = HDD.GetColumnValue("sy_pgs", "pageset_name", "pageset_id='" + strPagesetRowId.Replace("'", "''") + "'");
        string strPageSetHeading = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_pgs", "pageset_name", "af_row_id = '" + strPagesetRowId.Replace("'", "''") + "'");
        lblHeading.Text = "" + GetPageIcons(strPagesetRowId.Replace("'", "''")).Text + "<span style='vertical-align:middle;'>" + strPageSetHeading + "</span>&nbsp;"; // Modified by srivatsan
        //lblHeading.ID = "lblHeading";
        htc.Controls.Add(lblHeading);
        if (Create)
            htc.Controls.Add(getAddNewButton(strPagesetRowId, "Top"));

        if (strPagesetRowId.Trim().ToLower() == "c6e7de1b8b5f0835") // Added by srivatsan for View All Notes feature in notes section
        {
            if (rowcount > 0)
            {
                HtmlInputButton btnviewnotes = new HtmlInputButton();
                btnviewnotes.Attributes.Add("onclick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btn_viewall_notes_top','Loading...'); disableThis('ctl00_ContentPlaceHolder3_btn_viewall_notes_bottom','Loading...'); window.location.href='viewAllNotes.aspx?PK=" + HttpContext.Current.Request.QueryString["PK"] + "&mn=" + HttpContext.Current.Request.QueryString["mn"] + "'");
                btnviewnotes.ID = "btn_viewall_notes_top";
                btnviewnotes.Value = "View All";
                htc.Controls.Add(btnviewnotes);
            }
        }

        htc.Height = "15px";
        htc.VAlign = "middle";
        int iColSpan = colCount - 1;
        //if (Create) iColSpan++;
        //if (Edit) iColSpan++;
        //if (Delete) iColSpan++;
        iColSpan++;//if (Create || Edit || Delete) 

        htr.Cells.Add(htc);
        htr.Attributes.Add("class", "grid_header_light");
        htTable.Rows.Add(htr);
        htTable.Width = "100%";
        htTable.Border = 0;
        HtmlTableRow htRow1 = new HtmlTableRow();
        HtmlTableRow htRow = new HtmlTableRow();
        HtmlTableCell htCell = new HtmlTableCell();
        HtmlTableCell htCell1 = new HtmlTableCell();
        htCell.Controls.Add(htTable);
        htCell.ColSpan = iColSpan;
        htRow.Cells.Add(htCell);

        //HtmlTableRow htrAdd = new HtmlTableRow();
        //HtmlTableCell htcAdd = new HtmlTableCell();
        //htcAdd.Controls.Add(btnAdd);
        //htrAdd.Cells.Add(htcAdd);
        //htTable.Rows.Add(htrAdd);

        htCell1.Height = "25px";
        htRow1.Cells.Add(htCell1);
        hta.Controls.Add(htRow1);
        hta.Controls.Add(htRow);
    }

    private void addTableRow(string strPagesetRowId, ref HtmlTable hta, int colCount, bool create, bool edit, bool delete,int RowCount)
    {
        HtmlTableRow htr = new HtmlTableRow();
        HtmlTableCell htc = new HtmlTableCell();
        htc.Height = "15px";
        if (create)
        {
            htc.Controls.Add(new LiteralControl("&nbsp;"));
            htc.Controls.Add(getAddNewButton(strPagesetRowId, ""));
            htc.Align = "Left";
        }

        if (strPagesetRowId.Trim().ToLower() == "c6e7de1b8b5f0835") // Added by srivatsan for View All Notes feature in notes section
        {
            if (RowCount > 0)
            {
                HtmlInputButton btnviewnotes = new HtmlInputButton();
                btnviewnotes.Attributes.Add("onclick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btn_viewall_notes_bottom','Loading...'); disableThis('ctl00_ContentPlaceHolder3_btn_viewall_notes_top','Loading...'); window.location.href='viewAllNotes.aspx?PK=" + HttpContext.Current.Request.QueryString["PK"] + "&mn=" + HttpContext.Current.Request.QueryString["mn"] + "'");
                btnviewnotes.ID = "btn_viewall_notes_bottom";
                btnviewnotes.Value = "View All";
                htc.Controls.Add(btnviewnotes);
            }
        }

        htc.Attributes.Add("Class", "Grid_FooterAddNew");
        //if (hta.Rows.Count > 0) htc.ColSpan = hta.Rows[hta.Rows.Count - 1].Cells.Count;// +additionalColumns;        
        int iColSpan = colCount - 1;
        //if (create) iColSpan++;
        //if (edit) iColSpan++;
        //if (delete) iColSpan++;
        iColSpan++;//if (create || edit || delete)
        htc.ColSpan = iColSpan;
        htr.Cells.Add(htc);
        hta.Rows.Add(htr);
    }

    public bool hasChild(ref DataSet PageInfo)
    {
        bool bReturn = false;

        try
        {
            HDD = new HDDatabase();
            string sObject_id = PageInfo.Tables["Page"].Rows[0]["object_id"].ToString();
            string sSQL = "select * from sy_obj_mas_detail where master_obj='" + sObject_id + "'";
            DataTable dt = HDD.GetDataTable(sSQL);
            if (dt != null)
                if (dt.Rows.Count > 0)
                    bReturn = true;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("hasChild : Error : " + ex.Message);
            bReturn = false;
        }

        return bReturn;
    }

    public bool BuildGrid(DataSet dseObj, string strPagesetRowId, HtmlForm frmObj, bool Create, bool Edit, bool Delete, ref DataSet dsPageInfo, ref Hashtable hsDatatype)
    {
        HDS = new security();
        bool blnStatus = true;
        bool blnActions = false; // Added by srivatsan for Actions
        int RowCount = GetRowCount(dseObj); // Added by srivatsan for getting row count of data
        DataRow[] drractions = null;
        DataTable dtaObj = null;
        if (HttpContext.Current.Request["PK"] == null)
            dtaObj = ApplyPaging(dseObj.Tables[0], frmObj);
        else
            dtaObj = dseObj.Tables[0];

        HtmlTable hta = new HtmlTable();
        hta.Width = "100%";
        hta.CellSpacing = 0;
        hta.CellPadding = 0;
        hta.Border = 0;
        string strMenuRowId = "";
        if (frmObj.Page.Request.QueryString["mn"].ToString() != null)
        {
            strMenuRowId = frmObj.Page.Request.QueryString["mn"].ToString();
        }
        /********* Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts *********/
        HDDatabase HDD = new HDDatabase();
        if (strPagesetRowId == "aa922f981c2500e0") // Pageset_id = 'task_config'
            strMenuRowId = HDD.GetColumnValue("select af_row_id from sy_mnu where pageset_id='" + strPagesetRowId + "'");
        HDD = null;
        /********* End of Task & Alerts *********/
        hta.Attributes.Add("Class", "Grid_Table");
        if (HttpContext.Current.Request["PK"] != null)
            addHeaderForChildGrids(ref hta, strPagesetRowId, Create, Edit, Delete, dtaObj.Columns.Count,RowCount);
        blnActions = CanShowActionButton(ref drractions, dsPageInfo); // Added by srivatsan for Actions
        HeaderRow(dtaObj, hta, Create, Edit, Delete, hsDatatype,blnActions);
        bool IsAdminConsole = HDS.allRightsForNGMODEL();
        bool bHasChild = hasChild(ref dsPageInfo);
        DataRow(dtaObj, strPagesetRowId, hta, strMenuRowId, frmObj, getEditPage(HDD, strMenuRowId), Create, Edit, Delete, ref dsPageInfo, ref hsDatatype, IsAdminConsole, bHasChild,blnActions,drractions);

        HtmlTableCell htcObj;
        
        // if the grid is for Notes add grid to notes' td else to the original td
        if (strPagesetRowId.ToLower() == "c6e7de1b8b5f0835" && frmObj.Page.Request.QueryString["pk"] != null) // Added by srivatsan on Sep 29 2009 For notes checking // Modified by 'Imran Gani' on 19-Jul-2013, to check PK - master data
        {
            htcObj = (HtmlTableCell)DDI.FindControl(frmObj.Controls, "td_dynamic_notes");
        }
        else
        {
            htcObj = (HtmlTableCell)DDI.FindControl(frmObj.Controls, "tdDisplayGrid");
        }

        //HtmlTableCell htcObj = (HtmlTableCell)DDI.FindControl(frmObj.Controls, "tdDisplayGrid");//HtmlTableCell htcObj = (HtmlTableCell)frmObj.FindControl("tdDisplayGrid");

        htcObj.Controls.Add(hta);

        if (HttpContext.Current.Request["PK"] != null)
            addTableRow(strPagesetRowId, ref hta, dtaObj.Columns.Count, Create, Edit, Delete,RowCount);
        return blnStatus;
    }

    private DataTable ApplyPaging(DataTable dtaObj, HtmlForm frmObj)
    {
        int intCurrentPage = 1;
        int iTotalRecords = 0;
        //if (frmObj.FindControl("ContentPlaceHolder3").FindControl("hihCurrentPageId") != null)//if (frmObj.FindControl("hihCurrentPageId") != null)
        HtmlInputHidden hihObj = null;

        hihObj = (HtmlInputHidden)DDI.FindControl(frmObj.Controls, "hihTotalRecordCount");
        if (hihObj != null)
        {
            iTotalRecords = int.Parse(hihObj.Value);
        }
        if (DDI.FindControl(frmObj.Controls, "hihCurrentPageId") != null)
        {
            hihObj = (HtmlInputHidden)DDI.FindControl(frmObj.Controls, "hihCurrentPageId");
            intCurrentPage = Convert.ToInt32(hihObj.Value);
        }
        int intEndRecNo = intCurrentPage * GlobalValues.intNoOfRecordsPerPage;
        if (intEndRecNo > iTotalRecords)
        {
            intEndRecNo = iTotalRecords;
        }

        int intStartRecNo = (intCurrentPage - 1) * GlobalValues.intNoOfRecordsPerPage;
        if (intStartRecNo != 0 && intStartRecNo >= intEndRecNo)
        {
            intCurrentPage = intCurrentPage - 1;
            hihObj.Value = intCurrentPage.ToString();
            intStartRecNo = (intCurrentPage - 1) * GlobalValues.intNoOfRecordsPerPage;
        }

        //DataTable dtaObjRet = CopyTable(dtaObj, intStartRecNo, intEndRecNo);
        //UpdatePagingButtons(frmObj, intCurrentPage, iTotalRecords); // Commented by 'Imran Gani' on 24-Sep-2014, to avoid paging button
        //return dtaObjRet;
        return dtaObj;
    }

    private DataTable CopyTable(DataTable dtaSource, int intStartRecNo, int intEndRecNo)
    {
        DataTable dtaTarget = dtaSource.Clone();
        for (int i = intStartRecNo; i < intEndRecNo; i++)
            dtaTarget.ImportRow(dtaSource.Rows[i]);
        #region "Commented"
        //changed by Jeya Prabha on 28-Sep-2007 
        //{

        //    DataRow droObj = dtaTarget.NewRow();
        //    for (int j = 0; j < dtaSource.Columns.Count; j++)
        //    {
        //        if (dtaSource.Rows[i][j].ToString() == "")
        //        {
        //            droObj[j] = DBNull.Value;
        //        }
        //        else
        //        {
        //            droObj[j] = dtaSource.Rows[i][j].ToString();
        //        }
        //    }
        //    dtaTarget.Rows.Add(droObj);
        //} 
        #endregion
        return dtaTarget;
    }

    /// <summary>
    /// added on 17-Sep-2007 by Jeya Prabha
    /// This function sets the record information to the label
    /// </summary>
    /// <param name="frmObj">form object</param>
    /// <param name="intCurrentPage">current page number</param>
    /// <param name="intRecCount">total record count</param>
    private void setRecordInfo(HtmlForm frmObj, int intCurrentPage, int intRecCount)
    {
        //Label lblRecordInfo = (Label)frmObj.FindControl("ContentPlaceHolder3").FindControl("lblRecordNoInfo");
        Label lblRecordInfo = (Label)DDI.FindControl(frmObj.Controls, "lblRecordNoInfo");

        if (lblRecordInfo != null)
        {
            int iRecStart = 0;
            if (intRecCount > 0)
            {
                iRecStart = (intCurrentPage - 1) * GlobalValues.intNoOfRecordsPerPage;
                iRecStart = iRecStart + 1;
            }
            int iRecEnd = intCurrentPage * GlobalValues.intNoOfRecordsPerPage;
            if (iRecEnd > intRecCount)
                iRecEnd = intRecCount;

            if (iRecStart == iRecEnd)
                if (iRecStart==0)
                {
                    lblRecordInfo.Text = "";
                }
                else
                    lblRecordInfo.Text = "Showing record " + iRecEnd + " of " + intRecCount;
            else
                lblRecordInfo.Text = "Showing record(s) " + iRecStart + " to " + iRecEnd + " of " + intRecCount.ToString();
        }
    }

    private void pagingButtons(int CurrentPage, int LastPage, int RecordCount, ImageButton First, ImageButton Prev, ImageButton Next, ImageButton Last)
    {
        string sImageURL = "Images/navi_disabled.gif";

        if (RecordCount <= GlobalValues.intNoOfRecordsPerPage)
        {
            First.Visible = false;
            Next.Visible = false;
            Prev.Visible = false;
            Last.Visible = false;
        }
        else
        {
            if (CurrentPage == 1)
            {
                First.Enabled = false;
                //First.ImageUrl = sImageURL;  
                First.ImageUrl = "Images/first_disabled.GIF";
                Prev.Enabled = false;
                //Prev.ImageUrl = sImageURL; 
                Prev.ImageUrl = "Images/back_disabled.GIF";
            }

            if (CurrentPage == LastPage)
            {
                Next.Enabled = false;
                //Next.ImageUrl = sImageURL;  
                Next.ImageUrl = "Images/front_disabled.GIF";
                Last.Enabled = false;
                //Last.ImageUrl = sImageURL;
                Last.ImageUrl = "Images/last_disabled.GIF";
            }
        }
    }

    private bool UpdatePagingButtons(HtmlForm frmObj, int intCurrentPage, int intRecCount)
    {
        bool blnStatus = true;

        //GlobalValues.intNoOfRecordsPerPage = int.Parse(this.HDD.getAcrMemValue("3813ac7202378893", "1"));

        int intLastPage = intRecCount / GlobalValues.intNoOfRecordsPerPage;
        if (intRecCount % GlobalValues.intNoOfRecordsPerPage > 0)
        {
            intLastPage = intLastPage + 1;
        }

        ImageButton btnFObj = (ImageButton)DDI.FindControl(frmObj.Controls, "btnFirst");
        ;// Button btnObj = (Button)frmObj.FindControl("btnFirst");
        btnFObj.Attributes.Add("onclick", "return moveGridPage('1')");

        ImageButton btnNObj = (ImageButton)DDI.FindControl(frmObj.Controls, "btnNext");//btnObj = (Button)frmObj.FindControl("btnNext");
        btnNObj.Attributes.Add("onclick", "return moveGridPage('" + (intCurrentPage + 1).ToString() + "')");

        ImageButton btnPObj = (ImageButton)DDI.FindControl(frmObj.Controls, "btnPrev");//btnObj = (Button)frmObj.FindControl("btnPrev");
        btnPObj.Attributes.Add("onclick", "return moveGridPage('" + (intCurrentPage - 1).ToString() + "')");

        ImageButton btnLObj = (ImageButton)DDI.FindControl(frmObj.Controls, "btnLast");//btnObj = (Button)frmObj.FindControl("btnLast");
        btnLObj.Attributes.Add("onclick", "return moveGridPage('" + intLastPage.ToString() + "')");

        HtmlInputHidden hihObj = (HtmlInputHidden)DDI.FindControl(frmObj.Controls, "hihLastPageId");//HtmlInputHidden hihObj = (HtmlInputHidden)frmObj.FindControl("hihLastPageId");
        hihObj.Value = intLastPage.ToString();

        Label lblObj = (Label)DDI.FindControl(frmObj.Controls, "lblPageNoInfo");//Label lblObj = (Label)frmObj.FindControl("lblPageNoInfo");
        if (intLastPage == 0)
            intLastPage = 1;
        if (intCurrentPage == 0)
            intCurrentPage = 1;

        if (intCurrentPage != intLastPage && (intLastPage != 1 || intCurrentPage != 1))
            lblObj.Text = "Page " + intCurrentPage.ToString() + " of " + intLastPage.ToString();

        pagingButtons(intCurrentPage, intLastPage, intRecCount, btnFObj, btnPObj, btnNObj, btnLObj);

        //if (intRecCount != 0)
            setRecordInfo(frmObj, intCurrentPage, intRecCount);

        return blnStatus;
    }

    private void addHtmlCell(HtmlTableRow htr, string ColumnName, string tableName,/*srivatsan*/ string datatype)
    {
        HtmlTableCell htc = new HtmlTableCell();
        LinkButton lb = new LinkButton();
        lb.Attributes.Add("class", "mbLink");
        lb.OnClientClick = "javascript:setSortData('" + tableName + "','" + ColumnName + "');";
        //htc.Controls.Add(new LiteralControl(ColumnName));
        lb.Text = HttpUtility.HtmlEncode(ColumnName);

        if (isBeingSorted(tableName, ColumnName))
        {
            bool isDesc = isDescending();
            lb.ToolTip = isDesc ? "Sorted Descending" : "Sorted Ascending";
            htc.Controls.Add(lb);
            htc.Controls.Add(new LiteralControl("&nbsp;<img " + (isDesc == true ? "src=\"Images/sort_down.gif\"" : "src=\"Images/sort_up.gif\"") + " border=\"0\" />"));
        }
        else
        {
            htc.Controls.Add(lb);
        }
        if (datatype.ToLower() != "tx" && datatype.ToLower() != "da" && datatype.ToLower() != "dt" && datatype.ToLower() != "bo")   // added by srivatsan Apr02
        {
            htc.Align = "right";
        }
        else
        {
            htc.Align = "left";
        }
        htc.VAlign = "middle";
        if (ColumnName == "&nbsp;")
            htc.Width = "25px";
        htc.Attributes.Add("class","Grid_Header_Cell");
        htr.Cells.Add(htc);
    }
    private bool isDescending()
    {
        if (HttpContext.Current.Session["datasort"] == null)
            return false;
        string datasort = HttpContext.Current.Session["datasort"].ToString();
        if (datasort == "")
            return false;
        return datasort.EndsWith(" desc");
    }
    private bool isBeingSorted(string tableName, string colName)
    {
        if (HttpContext.Current.Session["datasort"] == null)
            return false;
        string datasort = HttpContext.Current.Session["datasort"].ToString();
        if (datasort == "")
            return false;
        return (getTableName(datasort) == tableName && colName == getColName(datasort));
    }
    private bool HeaderRow(DataTable dtaObj, HtmlTable htaObj, bool Create, bool Edit, bool Delete, Hashtable datatype,bool blnactions)
    {
        bool blnStatus = true;
        HtmlTableRow htr = new HtmlTableRow();
        string strColName = "";
        for (int i = 0; i < dtaObj.Columns.Count; i++)
        {
            HtmlTableCell htc = new HtmlTableCell();
            HtmlTableCell htcCopy = null;
            strColName = dtaObj.Columns[i].ColumnName.ToString();
            //string strdatatype = dtaObj.Columns[i].DataType.FullName;

            //strColName = "<a href=\"" + HttpContext.Current.Request.Url.ToString() + "\" onClick=\"javascript:setSortData('ss');return true;\">" + dtaObj.Columns[i].ColumnName.ToString() + "</a>"; 

            if (dtaObj.Columns[i].ColumnName.ToLower() == "keys")
            {
                //if (Create || Edit) addHtmlCell(htr, "&nbsp;");
                ////{
                ////    htc.Controls.Add(new LiteralControl("Edit"));
                ////    htr.Cells.Add(htc);
                ////}

                //if (Create) addHtmlCell(htr, "&nbsp;");
                ///*{
                //    htc = new HtmlTableCell();
                //    htc.Controls.Add(new LiteralControl("Copy"));
                //    htr.Cells.Add(htc);
                //}*/

                //if (Delete) addHtmlCell(htr, "&nbsp;");
                ////{
                if (Create || Edit || Delete || blnactions)
                {
                    HtmlTable ht = new HtmlTable();
                    HtmlTableRow htrr = new HtmlTableRow();
                    HtmlTableCell htcc = new HtmlTableCell();
                    htcc.Controls.Add(new LiteralControl("&nbsp;"));
                    htrr.Cells.Add(htcc);
                    ht.Rows.Add(htrr);
                    htcc = new HtmlTableCell();
                    ht.Border = 0;
                    ht.CellPadding = 0;
                    ht.CellSpacing = 0;
                    htcc.Controls.Add(ht);
                    htcc.Align = "right";
                    htr.Cells.Add(htcc);
                }
            }
            else
            {
                string strhashdatatype = datatype[strColName].ToString();
                addHtmlCell(htr, strColName, dtaObj.TableName, strhashdatatype);
            }
        }
        /*if (drMenuRights["is_remove"].ToString() == true.ToString())
        {
            HtmlTableCell htcDelete = new HtmlTableCell();
            htcDelete.Controls.Add(new LiteralControl("Delete"));
            htr.Cells.Add(htcDelete);
        }*/
        htr.Attributes.Add("Class", "Grid_Header");

        htaObj.Rows.Add(htr);
        return blnStatus;
    }

    private bool DataRow(DataTable dtaObj, string strPagesetRowId, HtmlTable htaObj, string strMenuRowId)
    {
        bool blnStatus = true;
        string strKey = "";
        string strText = "";
        for (int i = 0; i < dtaObj.Rows.Count; i++)
        {
            HtmlTableRow htr = new HtmlTableRow();
            for (int j = 0; j < dtaObj.Columns.Count; j++)
            {
                HtmlTableCell htc = new HtmlTableCell();
                HtmlTableCell htcCopy = null;
                string strCopyText = "";
                strText = dtaObj.Rows[i][j].ToString();
                if (dtaObj.Columns[j].ColumnName.ToLower() == "keys")
                {
                    strKey = strText;
                    strText = "<a href='DynamicScreen.aspx?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strText)
                        + "&mn=" + strMenuRowId + "'>Edit</a>";

                    htcCopy = new HtmlTableCell(); // added on 18-Sep-2007 by Jeya Prabha
                    strCopyText = "<a href='DynamicScreen.aspx?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strKey)
                        + "&mn=" + strMenuRowId + "&CPY=0'>Copy</a>";

                }
                htc.Controls.Add(new LiteralControl("<span class=\"defaultFont\">" + strText + "</span>"));
                htr.Cells.Add(htc);
                if (htcCopy != null) // added on 18-Sep-2007 by Jeya Prabha
                {
                    htcCopy.Controls.Add(new LiteralControl(strCopyText));
                    htr.Cells.Add(htcCopy);
                }
            }
            HtmlTableCell htcDelete = new HtmlTableCell();

            // changed by Jeya Prabha on 26-Sep-2007 for delete confirmation from user
            strText = "<a style='color:Blue;' ><u>Delete</u></a>";
            string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/'));
            sTemp = sTemp + "/DisplayGrid.aspx?pgs_id=" + strPagesetRowId + "&DPK=" + HttpUtility.UrlEncode(strKey) + "&mn=" + strMenuRowId;
            //htcDelete.Attributes.Add("onclick", "javascript:if(confirm('Are you sure you want to delete?')){window.location.replace('" + sTemp + "');};");
            //htcDelete.Attributes.Add("class", "cursor");
            ////strText = "<a href='DisplayGrid.aspx?pgs_id=" + strPagesetRowId + "&DPK=" + HttpUtility.UrlEncode(strKey) 
            ////    + "&mn=" + strMenuRowId + "'>Delete</a>";
            //htcDelete.Controls.Add(new LiteralControl(strText));
            //link button added on 01-Oct-2007
            LinkButton lnkDelete = new LinkButton();
            lnkDelete.Text = "Delete";
            lnkDelete.OnClientClick = "javascript:if(confirm('Are you sure you want to delete?')){window.location.replace('" + sTemp + "');};";
            htcDelete.Controls.Add(lnkDelete);
            htcDelete.Width = lnkDelete.Width.ToString();
            htr.Cells.Add(htcDelete);
            htr.Attributes.Add("Class", "Grid_Row");
            htaObj.Rows.Add(htr);
        }
        return blnStatus;
    }

    /// <summary>
    /// The function retrieves the pagename to which the the edit and copy operation will be redirected to.
    /// Created by Jeya Prabha on 18-Oct-2007
    /// </summary>
    /// <param name="MenuId"></param>
    /// <returns>The page name</returns>
    public string getEditPage(HDDatabase HDD, string strMenuRowId)
    {
        HDD = new HDDatabase();
        string sRet = "DynamicScreen.aspx"; //by default it will be "DynamicScreen.aspx"

        DataRow dr = CommonFunctions.GetDataRowFromPageInfo((HttpContext.Current.Request.QueryString["pgs_id"] == null ? "" : HttpContext.Current.Request.QueryString["pgs_id"].ToString()), "sy_mnu", "af_row_id = '" + strMenuRowId + "'");
        if (dr == null) dr = HDD.GetTableRow("select pageset_url, pageset_url_type from sy_mnu where af_row_id = '" + strMenuRowId + "'");
        
        if (dr != null)
            if (dr["pageset_url_type"].ToString() == "2")
            {
                sRet = dr["pageset_url"].ToString();
            }
            else if (dr["pageset_url_type"].ToString() == "4") // Added by srivatsan for transaction document
            {
                sRet = "TransDoc.aspx";
            }
        return sRet;
    }

    public string addMasterPrimaryKey(string URL)
    {
        try
        {
            ////if (HttpContext.Current.Request.QueryString["PK"] != null)
            ////    URL = URL + "&MK=" + HttpContext.Current.Request.QueryString["PK"] + @"";

            if (HttpContext.Current.Request.QueryString["PK"] != null)
            {
                //HttpContext.Current.Session["MK"] = HttpContext.Current.Session["PK"].ToString();
                URL = URL + "&MK=" + HttpContext.Current.Request.QueryString["PK"] + @"";
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("addMasterPrimaryKey : Error : " + ex.Message);
        }
        return URL;
    }

    private String getOverrideRowsKeyValues(DataTable dtObject, String Condition, String ColumnName)
    {
        String sRet = "";

        try
        {
            DataRow[] drr = dtObject.Select(Condition);

            foreach (DataRow dr in drr)
            {
                sRet = sRet + "'" + dr[ColumnName].ToString() + "',";
            }

            sRet = sRet.TrimEnd(',');
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getOverrideRowsKeyValues : Error : " + ex.Message);
        }

        return sRet;
    }

    public void getOverrideAccess(ref bool bEdit, ref bool bDelete, ref DataTable dtObject, ref String sEdit, ref String sDelete, ref String Edit_rowid, ref String Delete_rowid)
    {
        try
        {
            HDD = new HDDatabase();
            String sSql = "select * from sy_object_access_override where object='" + dtObject.TableName.Replace("'", "''") + "' and active='1';";
            String sKeyValues = getOverrideRowsKeyValues(dtObject, "", "keys");
            if (sKeyValues != "")
            {
                string FromTable = CommonFunctions.GetColValueFromPageInfo((HttpContext.Current.Request.QueryString["pgs_id"] == null ? "" : HttpContext.Current.Request.QueryString["pgs_id"].ToString()), "sy_pg", "page_table_name", "page_id='" + dtObject.TableName.Replace("'", "''") + "'");
                if (FromTable == "") FromTable = HDD.GetColumnValue("select page_table_name from sy_pg where page_id='" + dtObject.TableName.Replace("'", "''") + "'");
                sSql = sSql + "select * from " + FromTable + " where af_row_id in ( " + sKeyValues + ");";
            }

            //DataSet dsTemp = HDD.GetDataset("select * from sy_object_access_override where object='" + dtObject.TableName.Replace("'", "''") + "' and active='1';select * from " + HDD.GetColumnValue("select page_table_name from sy_pg where page_id='" + dtObject.TableName.Replace("'", "''") + "'") + " where af_row_id in ( " + getOverrideRowsKeyValues(dtObject, "", "keys") + ");");
            DataSet dsTemp = HDD.GetDataset(sSql);

            if (dsTemp.Tables.Count > 0)
            {
                foreach (DataRow dr in dsTemp.Tables[0].Rows)
                {
                    switch (dr["action"].ToString().ToLower())
                    {
                        case "edit":

                            if (sEdit == "")
                            {
                                sEdit = getOverrideRowsKeyValues(dsTemp.Tables[1], dr["condition"].ToString(), "af_row_id");
                            }
                            if (dr["mode"].ToString().ToLower() == "enable")
                            {
                                bEdit = true;
                            }
                            else if (dr["mode"].ToString().ToLower() == "disable")
                            {
                                bEdit = false;
                            }
                            Edit_rowid = dr["af_row_id"].ToString();

                            break;
                        case "delete":

                            if (sDelete == "")
                            {
                                sDelete = getOverrideRowsKeyValues(dsTemp.Tables[1], dr["condition"].ToString(), "af_row_id");
                            }
                            if (dr["mode"].ToString().ToLower() == "enable")
                            {
                                bDelete = true;
                            }
                            else if (dr["mode"].ToString().ToLower() == "disable")
                            {
                                bDelete = false;
                            }
                            Delete_rowid = dr["message"].ToString();

                            break;
                        default:
                            break;
                    }
                }
            }
            dsTemp.Dispose();
            dsTemp = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getOverrideAccess : Error : " + ex.Message);
        }

    }

    public bool DataRow(DataTable dtaObj, string strPagesetRowId, HtmlTable htaObj, string strMenuRowId, HtmlForm frmObj, string EditPage, bool Create, bool Edit, bool Delete, ref DataSet dsPageInfo, ref Hashtable hsDatatype, bool IsAdminConsole, bool HasChild, bool blnaction, DataRow[] drractions)
    {
        bool blnStatus = true;
        string strKey = "";
        string strText = "";
        int intCurrentPage = 1;
        sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
        if (DDI.FindControl(frmObj.Controls, "hihCurrentPageId") != null)
        {
            HtmlInputHidden hihObj = (HtmlInputHidden)DDI.FindControl(frmObj.Controls, "hihCurrentPageId");
            intCurrentPage = Convert.ToInt32(hihObj.Value);
        }
        bool bEditOverride = true;
        bool bDeleteOverride = false;
        String sEditKeyValues = "";
        String sDeleteKeyValues = "";
        String sEdit_RowId = "";
        String sDelete_RowId = "";

        if (strPagesetRowId == "5f4649e689509dea") // Added by 'Imran Gani' on Sep 18 2012 for Documents changes
            EditPage = "Documents.aspx";
        
        getOverrideAccess(ref bEditOverride, ref bDeleteOverride, ref dtaObj, ref sEditKeyValues, ref sDeleteKeyValues, ref sEdit_RowId, ref sDelete_RowId);
        for (int i = 0; i < dtaObj.Rows.Count; i++)
        {
            HtmlTableRow htr = new HtmlTableRow();
            for (int j = 0; j < dtaObj.Columns.Count; j++)
            {
                HtmlTableCell htc = new HtmlTableCell();
                if (dtaObj.Rows[i][j] == System.DBNull.Value)
                    strText = "&nbsp;";
                else
                {
                    if (strPagesetRowId == "5f4649e689509dea" && dtaObj.Columns[j].ColumnName.ToLower() == "file name") // Added by 'Imran Gani' on Dec 20 2012 for Documents file
                        strText = dtaObj.Rows[i][j].ToString();
                    else if (strPagesetRowId == "6c1d1024879ba702" && dtaObj.Columns[j].ColumnName.ToLower() == "link") // Added by 'Imran Gani' on Dec 20 2012 for Documents file
                        strText = dtaObj.Rows[i][j].ToString();
                    else
                        strText = HttpUtility.HtmlEncode(dtaObj.Rows[i][j].ToString());
                }
                if (dtaObj.Columns[j].ColumnName.ToLower() == "keys")
                {
                    strKey = strText;
                    HtmlTableCell htcc = new HtmlTableCell();
                    HtmlTableRow htrr = new HtmlTableRow();

                    #region Old Code commented by 'Imran Gani' on 06-May-2013, to avoid server button for postback control
                    //if (Create || Edit)
                    //{
                    //    if (sEditKeyValues.Contains(strText))
                    //    {
                    //        if (bEditOverride)
                    //        {
                    //            strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strText)
                    //                + "&mn=" + strMenuRowId + @"";
                    //            strText = addMasterPrimaryKey(strText);
                    //        }
                    //        else
                    //        {
                    //            strText = @"" + "NoAccess.aspx" + @"?pgs_id=" + strPagesetRowId + "&PK=" + sEdit_RowId
                    //                + "&mn=" + strMenuRowId + @"";
                    //        }
                    //    }
                    //    else
                    //    {
                    //        strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strText)
                    //            + "&mn=" + strMenuRowId + @"";
                    //        strText = addMasterPrimaryKey(strText);
                    //    }

                    //    ImageButton lnkedit = new ImageButton();
                    //    lnkedit.ImageUrl = "images/edit.gif";
                    //    lnkedit.PostBackUrl = strText;
                    //    lnkedit.ToolTip = "Edit";
                    //    lnkedit.CausesValidation = false;
                    //    lnkedit.AlternateText = "Edit";//sanal on Sep 02, 2011 to avoid the display of "Submit Query" in FF
                    //    lnkedit.Attributes.Add("onClick", "javascript:this.src='images/load.gif'");
                    //    if (!IsAdminConsole)
                    //        lnkedit.ID = "E_" + strKey;
                    //    htcc.Width = "25px";

                    //    htcc.Controls.Add(lnkedit);
                    //    htrr.Cells.Add(htcc);
                    //}

                    //if (Create) //changed by Prithi on 13 Oct 2008
                    //{
                    //    htcc = new HtmlTableCell(); // added on 18-Sep-2007 by Jeya Prabha
                    //    strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strKey)
                    //        + "&mn=" + strMenuRowId + @"&CPY=0";

                    //    strText = addMasterPrimaryKey(strText);

                    //    ImageButton lnkcopy = new ImageButton();
                    //    lnkcopy.ImageUrl = "images/copy.gif";
                    //    lnkcopy.PostBackUrl = strText;
                    //    lnkcopy.ToolTip = "Copy";
                    //    lnkcopy.CausesValidation = false;
                    //    lnkcopy.AlternateText = "Copy";//sanal on Sep 02, 2011 to avoid the display of "Submit Query" in FF
                    //    lnkcopy.Attributes.Add("onClick", "javascript:this.src='images/load.gif'");
                    //    if (!IsAdminConsole)
                    //        lnkcopy.ID = "C_" + strKey;
                    //    htcc.Width = "25px";
                    //    htcc.Controls.Add(lnkcopy);

                    //    htrr.Cells.Add(htcc);
                    //}
                    #endregion

                    if (Edit) //if (Create || Edit) // commented by 'Imran Gani' on 03-Dec-2013 
                    {
                        if (sEditKeyValues.Contains(strText))
                        {
                            if (bEditOverride)
                            {
                                strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strText) + "&mn=" + strMenuRowId + @"";
                                strText = addMasterPrimaryKey(strText);
                            }
                            else
                                strText = @"" + "NoAccess.aspx" + @"?pgs_id=" + strPagesetRowId + "&PK=" + sEdit_RowId + "&mn=" + strMenuRowId + @"";
                        }
                        else
                        {
                            strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strText) + "&mn=" + strMenuRowId + @"";
                            strText = addMasterPrimaryKey(strText);
                        }

                        HyperLink lnkedit = new HyperLink();
                        lnkedit.ImageUrl = "images/edit.gif";
                        lnkedit.ToolTip = "Edit";
                        lnkedit.NavigateUrl = strText;
                        if (!IsAdminConsole)
                            lnkedit.ID = "E_" + strKey;
                        //lnkedit.Attributes.Add("onClick", "javascript:$('#ctl00_ContentPlaceHolder3_" + lnkedit.ID + "').find('img').attr('src', 'images/load.gif');");
                        lnkedit.Attributes.Add("onClick", "javascript:$(this).children('img').attr('src', 'images/load.gif');");
                        htcc.Controls.Add(lnkedit);
                        htcc.Width = "25px";
                        htrr.Cells.Add(htcc);
                    }

                    if (Create) 
                    {
                        htcc = new HtmlTableCell();
                        strText = @"" + EditPage + @"?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(strKey) + "&mn=" + strMenuRowId + @"&CPY=0";
                        strText = addMasterPrimaryKey(strText);

                        HyperLink lnkcopy = new HyperLink();
                        lnkcopy.ImageUrl = "images/copy.gif";
                        lnkcopy.ToolTip = "Copy";
                        lnkcopy.NavigateUrl = strText;
                        if (!IsAdminConsole)
                            lnkcopy.ID = "C_" + strKey;
                        //lnkcopy.Attributes.Add("onClick", "javascript:$('#ctl00_ContentPlaceHolder3_" + lnkcopy.ID + "').find('img').attr('src', 'images/load.gif');");
                        lnkcopy.Attributes.Add("onClick", "javascript:$(this).children('img').attr('src', 'images/load.gif');");
                        htcc.Controls.Add(lnkcopy);
                        htcc.Width = "25px";
                        htrr.Cells.Add(htcc);
                    }
                    if (Delete)
                    {
                        #region commented code
                        //htcc = new HtmlTableCell();
                        //strText = "<a style='color:Blue;' ><u>Delete</u></a>";
                        //string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/'));
                        //sTemp = sTemp + HttpContext.Current.Request.Url.AbsolutePath.Substring(HttpContext.Current.Request.Url.AbsolutePath.LastIndexOf("/"), (HttpContext.Current.Request.Url.AbsolutePath.Length - HttpContext.Current.Request.Url.AbsolutePath.LastIndexOf("/")));
                        //sTemp = sTemp + "?pgs_id=" + strPagesetRowId + "&DPK=" + strKey + "&mn=" + strMenuRowId + "&cp=" + intCurrentPage;

                        //sTemp = addMasterPrimaryKey(sTemp);

                        //ImageButton lnkDelete = new ImageButton();
                        //lnkDelete.Click += new ImageClickEventHandler(lnkDelete_Click);
                        //lnkDelete.ImageUrl = "images/delete.gif";
                        //lnkDelete.ToolTip = "Delete";
                        //lnkDelete.CausesValidation = false;
                        //lnkDelete.Attributes.Add("onClick", "this.src='images/load.gif'");
                        //if (!IsAdminConsole)
                        //    lnkDelete.ID = "D_" + strKey;
                        //if (HasChild)
                        //    lnkDelete.OnClientClick = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){window.location.replace(""" + sTemp + @""");}else{return false;};";
                        //else
                        //    lnkDelete.OnClientClick = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){window.location.replace(""" + sTemp + @""");}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")";




                        ////Added by srivatsan

                        //htcc = new HtmlTableCell();
                        //strText = "<a style='color:Blue;' ><u>Delete</u></a>";
                        //string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/'));
                        //sTemp = sTemp + HttpContext.Current.Request.Url.AbsolutePath.Substring(HttpContext.Current.Request.Url.AbsolutePath.LastIndexOf("/"), (HttpContext.Current.Request.Url.AbsolutePath.Length - HttpContext.Current.Request.Url.AbsolutePath.LastIndexOf("/")));
                        //sTemp = sTemp + "?pgs_id=" + strPagesetRowId + "&DPK=" + strKey + "&mn=" + strMenuRowId + "&cp=" + intCurrentPage;
                        //sTemp = addMasterPrimaryKey(sTemp);

                        //ImageButton lnkDelete = new ImageButton();
                        //lnkDelete.Click += new ImageClickEventHandler(lnkDelete_Click);
                        //lnkDelete.ImageUrl = "images/delete.gif";
                        //lnkDelete.ToolTip = "Delete";
                        //lnkDelete.CausesValidation = false;
                        //lnkDelete.Attributes.Add("onClick", "this.src='images/load.gif'");
                        //if (!IsAdminConsole)
                        //    lnkDelete.ID = "D_" + strKey;
                        //if (HttpContext.Current.Request.QueryString["PK"] != null)
                        //{
                        //    if (HasChild)
                        //        lnkDelete.OnClientClick = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){window.location.replace(""" + sTemp + @""");}else{return false;};";
                        //    else
                        //        lnkDelete.OnClientClick = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){window.location.replace(""" + sTemp + @""");}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")";
                        //}
                        //else
                        //{
                        //    if (HasChild)
                        //        lnkDelete.OnClientClick = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";
                        //    else
                        //        lnkDelete.OnClientClick = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")";
                        //}

                        //htcc.Controls.Add(lnkDelete);
                        //htcc.Width = "25px";
                        //htrr.Cells.Add(htcc);

                        #endregion

                        htcc = new HtmlTableCell();
                        #region For User Deletion. Added by 'Imran Gani' on 26-Mar-2014
                        if (strPagesetRowId == "8c2cb032c3b3516d")
                        {
                            string sCURL = HttpContext.Current.Request.Url.AbsoluteUri;
                            string sActionUrl = @"MB_ActionHandler.aspx?pgs_id=" + strPagesetRowId + "&DPK=" + HttpUtility.UrlEncode(strKey) + "&action=usr_del&curl=" + HttpUtility.UrlEncode(sCURL) + @"";

                            HyperLink lnkDelete = new HyperLink();
                            lnkDelete.ImageUrl = "images/delete.gif";
                            lnkDelete.ToolTip = "Delete";
                            lnkDelete.NavigateUrl = sActionUrl;
                            if (!IsAdminConsole)
                                lnkDelete.ID = "D_" + strKey;
                            lnkDelete.Attributes.Add("onClick", @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){return true;}else{return false;};");
                            htcc.Controls.Add(lnkDelete);
                        }
                        #endregion
                        else
                        {
                            strText = "<a style='color:Blue;' ><u>Delete</u></a>";
                            string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/'));
                            sTemp = sTemp + HttpContext.Current.Request.Url.AbsolutePath.Substring(HttpContext.Current.Request.Url.AbsolutePath.LastIndexOf("/"), (HttpContext.Current.Request.Url.AbsolutePath.Length - HttpContext.Current.Request.Url.AbsolutePath.LastIndexOf("/")));
                            sTemp = sTemp + "?pgs_id=" + strPagesetRowId + "&DPK=" + strKey + "&mn=" + strMenuRowId + "&cp=" + intCurrentPage;
                            sTemp = addMasterPrimaryKey(sTemp);

                            //Label lnkDelete = new Label();
                            ImageButton lnkDelete = new ImageButton();
                            lnkDelete.ImageUrl = "images/delete.gif";
                            //lnkDelete.Text = "Delete";
                            //lnkDelete.CssClass = "SearchPopup";
                            lnkDelete.ToolTip = "Delete";
                            lnkDelete.AlternateText = "Delete";//sanal on Sep 02, 2011 to avoid the display of "Submit Query" in FF
                            lnkDelete.Click += new ImageClickEventHandler(lnkDelete_Click);

                            //string deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){window.location.href=(""" + sTemp + @"""); DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";
                            //string deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){window.location.href=(""" + sTemp + @"""); DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                            string deleteURLChild = "";
                            string deleteURL = "";
                            if (sDeleteKeyValues.Contains(strKey))
                            {
                                if (bDeleteOverride)
                                {
                                    if (HttpContext.Current.Request.QueryString["PK"] != null)
                                    {
                                        deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){DeleteClick('" + strKey + "','" + intCurrentPage + "');UpdateMK('" + HttpContext.Current.Request.QueryString["PK"].ToString() + "'); UpdateDeletePageset('" + strPagesetRowId + "'); }else{return false;};";
                                        deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "'); UpdateMK('" + HttpContext.Current.Request.QueryString["PK"].ToString() + "'); UpdateDeletePageset('" + strPagesetRowId + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                                    }
                                    else
                                    {
                                        deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";
                                        deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                                    }
                                    if (strPagesetRowId == "896d3320756939fe") // Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security
                                        deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: There are users associated to this business unit. Deletion will lead to access restriction for such users. Do you want to continue?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                                }
                                else
                                {
                                    deleteURLChild = @"javascript:alert(""" + includeJavascriptEscapes(sDelete_RowId) + @""");return false;";
                                    deleteURL = @"javascript:alert(""" + includeJavascriptEscapes(sDelete_RowId) + @""");return false;";
                                }
                            }
                            else
                            {
                                if (HttpContext.Current.Request.QueryString["PK"] != null)
                                {
                                    deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){DeleteClick('" + strKey + "','" + intCurrentPage + "');UpdateMK('" + HttpContext.Current.Request.QueryString["PK"].ToString() + "'); UpdateDeletePageset('" + strPagesetRowId + "'); }else{return false;};";
                                    deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "'); UpdateMK('" + HttpContext.Current.Request.QueryString["PK"].ToString() + "'); UpdateDeletePageset('" + strPagesetRowId + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                                }
                                else
                                {
                                    deleteURLChild = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: Child records will also be deleted."")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";
                                    deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                                }
                                if (strPagesetRowId == "896d3320756939fe") // Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security
                                    deleteURL = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dtaObj.Rows[i][1].ToString()) + @"' ?\r Note: There are users associated to this business unit. Deletion will lead to access restriction for such users. Do you want to continue?"")){DeleteClick('" + strKey + "','" + intCurrentPage + "');}else{return false;};";//@"javascript:return confirm(""Are you sure you want to delete '" + dtaObj.Rows[i][0].ToString() + @"' ?"")"; 
                            }

                            if (!IsAdminConsole)
                                lnkDelete.ID = "D_" + strKey;

                            if (HasChild)
                                //lnkDelete.Attributes.Add("onClick", "this.src='images/load.gif'; " + deleteURLChild + "");
                                lnkDelete.OnClientClick = deleteURLChild;
                            else
                                //lnkDelete.Attributes.Add("onClick", "this.src='images/load.gif'; " + deleteURL + "");
                                lnkDelete.OnClientClick = deleteURL;
                            
                            htcc.Controls.Add(lnkDelete);
                        }
                        htcc.Width = "25px";
                        htrr.Cells.Add(htcc);

                    }

                    if (blnaction) // Added by srivatsan for action button
                    {
                        htcc = new HtmlTableCell();

                        ImageButton imgaction = new ImageButton();
                        imgaction.ImageUrl = "images/action_16.gif";
                        imgaction.ID = "Ac_"+ strKey;
                        htcc.Controls.Add(imgaction);
                        Action ac = new Action();
                        htcc.Controls.Add(new LiteralControl("<br/>"));
                        ac.CreateActionDIV(ref htcc, drractions, imgaction.ID,strKey,false);
                        htcc.Width = "25px";
                        htrr.Controls.Add(htcc);
                    }


                    HtmlTable htt = new HtmlTable();
                    htt.Border = 0;
                    htt.CellSpacing = 0;
                    htt.CellPadding = 0;
                    htt.Rows.Add(htrr);
                    htc.Controls.Add(htt);
                    htc.Align = "left";
                    if (htrr.Cells.Count == 1)
                        htc.Width = "30px";
                    else if (htrr.Cells.Count == 2)
                        htc.Width = "55px";
                    else if (htrr.Cells.Count == 3)
                        htc.Width = "80px";
                    else if (htrr.Cells.Count == 4) // Added by srivatsan for Action button
                        htc.Width = "105px";
                    if (htrr.Cells.Count != 0)
                        htr.Cells.Add(htc);
                }
                else
                {
                    if (hsDatatype.Contains(dtaObj.Columns[j].ColumnName))
                    {
                        #region Old Code commented by 'Imran Gani' on 28-Feb-2014, to avoid 'if' statement and to use switch case.
                        ////if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "dt")
                        ////{
                        ////    if (strText != "" && strText != "&nbsp;")
                        ////        if (strText != "" && strText != "&nbsp;")
                        ////            strText = DDI.getUsersDT(strText, sUTC_Offset);
                        ////} //commented by srivatsan

                        //if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "dt")
                        //{
                        //    if (dtaObj.Columns[j].ColumnName.ToLower().Trim() == "modified at" || dtaObj.Columns[j].ColumnName.ToLower().Trim() =="created at")
                        //    {
                        //        if (strText != "" && strText != "&nbsp;")
                        //        {
                        //            if (strText != "" && strText != "&nbsp;")
                        //            {
                        //                //strText = DDI.getUsersDT(strText, sUTC_Offset);
                        //                Localization loc = new Localization();

                        //                strText = loc.getDateTime4TimeZone(strText, sUTC_Offset, false, true);
                        //            }
                        //        }
                        //    }
                        //    else
                        //    {
                        //        if (strText != "" && strText != "&nbsp;")
                        //            if (strText != "" && strText != "&nbsp;")
                        //                strText = DDI.getUsersDT(strText, sUTC_Offset);
                        //    }
                        //}

                        //else if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "cu")//sanal
                        //{
                        //    if (strText != "&nbsp;")
                        //        strText = DDI.manageCurrency(strText, currencyCode_Rate);
                        //}
                        //else if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "da")
                        //{
                        //    if (strText != "" && strText != "&nbsp;")
                        //        strText = manageDateTimeValues("da", strText);
                        //}

                        #region MyRegion
                        //if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "dt")
                        //{
                        //    if (strText != "" && strText != "&nbsp;")
                        //        strText = DDI.getUsersDT(strText, sUTC_Offset);
                        //}
                        //else if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "cu")//sanal
                        //    strText = DDI.manageCurrency(strText, currencyCode_Rate);
                        //else if (hsDatatype[dtaObj.Columns[j].ColumnName].ToString().ToLower() == "da")
                        //    strText = manageDateTimeValues("da", strText);
                        //if (strText.IndexOf(" ") != -1)
                        //    strText = DateTime.Parse(strText.Substring(0, strText.IndexOf(" "))).ToString("dd-MMM-yyyy"); ; 
                        #endregion
                        #endregion

                        #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
                        Localization loc = new Localization();
                        strText = loc.getLocaleFormattedValue(strText, hsDatatype[dtaObj.Columns[j].ColumnName].ToString(), dtaObj.Columns[j].ColumnName, sUTC_Offset, DDI, currencyCode_Rate);
                        loc = null;
                        #endregion
                    }

                    if (j == 1 && dtaObj.Columns.Contains("keys"))
                    {
                        #region MyRegion 
                        //string sViewPage = @"<a href=""DynamicScreen.aspx?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(dtaObj.Rows[i]["keys"].ToString())
                        //            + "&mn=" + strMenuRowId + @"&VMODE=1""><font color=""blue"">" + strText + "</font></a>";
                        //if (EditPage.ToLower() == "reportwizard.aspx")
                        //    sViewPage = @"<a href=""Report.aspx?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(dtaObj.Rows[i]["keys"].ToString())
                        //+ "&mn=" + strMenuRowId + @"&VMODE=1"" target=""_blank""><font face=""Arial"" color=""blue"">" + strText + "</font></a>";
                        //strText = @"<a href=""" + sViewPage + "?pgs_id=" + strPagesetRowId + "&PK=" + HttpUtility.UrlEncode(dtaObj.Rows[i]["keys"].ToString())
                        //+ "&mn=" + strMenuRowId + @"&VMODE=1""><font color=""blue"">" + strText + "</font></a>"; 
                        #endregion
                        if (strText.Trim() == "")
                            strText = "&nbsp;";
                        string sViewPage = @"<a href=""" + EditPage + "?pgs_id=" + strPagesetRowId + "&PK=" + dtaObj.Rows[i]["keys"].ToString() + "&MK=" + HttpContext.Current.Request.QueryString["PK"] + @""
                            + "&mn=" + strMenuRowId + @"&VMODE=1""><font color=""blue"">" + strText + "</font></a>";
                        //strText = "&nbsp;" + sViewPage;
                        strText = sViewPage; // modified by srivatsan
                    }
                    handleControlType(ref strText, ref dsPageInfo, ref dtaObj, j,i);//added by sanal on Nov 30, 2009
                    //htc.Controls.Add(new LiteralControl("&nbsp;" + strText + "&nbsp;"));
                    htc.Controls.Add(new LiteralControl(strText)); // modified by srivatsan
                    
                    setAlignment(ref htc, hsDatatype[dtaObj.Columns[j].ColumnName].ToString());
                    htr.Cells.Add(htc);
                }
                int intRow = (htaObj.Rows.Count + 1) % 2;
                htr.VAlign = "middle";
                htr.Height = "25px"; // sirvatsan
                htr.Attributes.Add("Class", "Grid_Row" + intRow.ToString());
                htr.Attributes.Add("onMouseOver", "this.className='Grid_Scroll_BG'");
                htr.Attributes.Add("onMouseOut", "this.className='" + "Grid_Row" + intRow.ToString() + "'");
                htaObj.Rows.Add(htr);
            }
            htaObj.Border = 0;
            addstyles(ref htr);
        }
        checkNoRecords(ref htaObj, ref dtaObj, Create, Edit, Delete);
        return blnStatus;
    }
    public void handleControlType(ref string strText, ref DataSet dsPageInfo,ref DataTable dtaObj,int columnCount,int rowCount)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (strText.Length > 0 && strText != "&nbsp;")
            {
                DataRow[] dr = dsPageInfo.Tables["Page Controls"].Select("control_name='" + dtaObj.Columns[columnCount].ColumnName + "'");
                if (dr.Length > 0 && dr[0]["control_html"].ToString().ToLower() == "em")
                {
                    //CommonFunctions cf = new CommonFunctions();
                    if (UseMaxBloxEmailCompose())
                    {
                        string strPagesetRowId = "";
                        if (dsPageInfo.Tables["PageSet"] != null)
                            if (dsPageInfo.Tables["PageSet"].Rows.Count > 0)
                                strPagesetRowId = dsPageInfo.Tables["PageSet"].Rows[0]["af_row_id"].ToString();
                        string strPK = dtaObj.Rows[rowCount]["keys"].ToString();
                        //Below line added by 'Imran Gani' on 22-Apr-2013, to get the menu id details from DB if not exist in URL.
                        string strMenuRowId = HttpContext.Current.Request.QueryString["mn"] != null ? HttpContext.Current.Request.QueryString["mn"].ToString() : HDD.GetColumnValue("select af_row_id from sy_mnu where pageset_id = '" + strPagesetRowId + "';");
                        string strCtrlid = dsPageInfo.Tables["Page Controls"].Select("control_name='" + dtaObj.Columns[columnCount].ColumnName + "'")[0]["control_attrib_id"].ToString();
                        string navURL = "ComposeEmail.aspx?pgs_id=" + strPagesetRowId + "&mn=" + strMenuRowId + "&PK=" + strPK + "&CnID=" + strCtrlid + "";
                        //if (HttpContext.Current.Request.QueryString["PK"] != null)
                        //{
                           // navURL = navURL + "&MK=" + HttpContext.Current.Request.QueryString["PK"].ToString() + "|"+dsPageInfo.Tables["PageKeys"].Rows[0]["master_obj"].ToString()+"|"+dsPageInfo.Tables["PageKeys"].Rows[0]["display_att"].ToString()+"";
                        //}
                        strText = "<a href= \""+navURL+"\" title=\"Send E-mail\">" + strText + "</a>";
                    }
                    else
                        strText = "<a href=\"mailto:" + strText + "\" title=\"Send E-mail\">" + strText + "</a>";
                    //cf = null;
                }
            }
        }
        catch (Exception e) { LogWriter.WriteLog("Error in handleControlType. " + e.Message); }
    }

    protected void lnkDelete_Click(object sender, ImageClickEventArgs e)
    {
        //throw new Exception("The method or operation is not implemented.");
    }
    public string manageDateTimeValues(string type, string input)
    {
        if (type.Trim() == "")
            return input;
        if (input.Length < 1)
            return input;
        string ret = input;
        try
        {
            switch (type)
            {
                case "da":
                    ret = MBLocalization.getLocalizedDate(HttpContext.Current.Session["userlocale"].ToString(), DateTime.Parse(input));
                    break;
                case "dt":
                    ret = MBLocalization.getLocalizedDateTime(HttpContext.Current.Session["userlocale"].ToString(), DateTime.Parse(input));
                    break;
                default:
                    ret = input;
                    break;
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in manageDateTimeValues. " + e.Message);
        }
        return ret;
    }
    public string includeJavascriptEscapes(string inp)
    {
        if (inp.Trim() == "")
            return inp;
        try
        {
            string[] orgChars = new string[] { "\\", "\'", "\"" };
            string[] replaces = new string[] { "\\\\", "\\'", "\\\"" };
            for (int i = 0; i < orgChars.Length; i++)
                inp = inp.Replace(orgChars[i], replaces[i]);
            return inp;
        }
        catch (Exception e)
        {
            return inp;
        }
    }
    public void setAlignment(ref HtmlTableCell htc, string datatype)
    {
        try
        {
            switch (datatype.ToUpper().Trim())
            {
                case "BO":
                case "DA":
                case "DT":
                case "TX":
                    htc.Align = "Left";
                    break;
                case "CU":
                case "DC":
                case "NU":
                case "AN":
                    htc.Align = "Right";
                    break;
                default:
                    htc.Align = "center";
                    break;
            }
        }
        catch (Exception e)
        {
        }
    }
    public void addstyles(ref HtmlTableRow htr)
    {
        //implemented by sanal to add borders on the left and right of the record grid on 13 Feb 2008
        if (htr.Cells.Count > 0)
            htr.Cells[0].Attributes.Add("class", "leftGrid");
        //if (htr.Cells.Count > 1)
        //{
        //    for (int i = 1; i < htr.Cells.Count - 1; i++)
        //        htr.Cells[i].Attributes.Add("class", "rightCell");//rightcell class is avaialable only in StandardBlue
        //}
        if (htr.Cells.Count > 1)
        {
            htr.Cells[htr.Cells.Count - 1].Attributes.Add("class", "rightGrid");
            if (htr.Cells[htr.Cells.Count - 1].InnerHtml=="")
            {
                htr.Cells[htr.Cells.Count - 1].InnerHtml = "&nbsp;";
            }
        }
    }
    private void checkNoRecords(ref HtmlTable htaObj, ref DataTable dtaObj, bool Create, bool Edit, bool Delete)
    {
        if (dtaObj.Rows.Count == 0)
        {
            HtmlTableCell htc = new HtmlTableCell();
            htc.Controls.Add(new LiteralControl("&nbsp;No records available."));
            HtmlTableRow htr = new HtmlTableRow();
            int iColSpan = dtaObj.Columns.Count - 1;
            iColSpan = iColSpan + 2;//if (Create)
            //if (Edit) iColSpan++;
            //if (Delete) iColSpan++;
            htc.ColSpan = iColSpan;
            htr.Cells.Add(htc);
            htr.Attributes.Add("Class", "Grid_Row1");
            htaObj.CellPadding = 0;
            htaObj.Rows.Add(htr);
        }
    }
    public string PageSetSelectSql(DataTable dtaPage, DataTable dtaPageKeys, DataTable dtaPageSrch, ref DataTable dtPageControls, ref Hashtable hsDatatype, string childField)
    {
        string strPageSql = "";

        string strTableNames = GetTableNames(dtaPage, dtaPageSrch);

        if (strTableNames != "")
        {
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            string sCustodianFilter = ""; // = objSec.QueryForCustodianFilter(); // commented by 'Imran Gani' on 05-June-2013 for Org Security
            if (sCustodianFilter.Trim() != "")
                //sAFAdmin += " and " + sCustodianFilter;

                if (!sCustodianFilter.StartsWith("or"))
                {
                    if (sAFAdmin.Trim() != "")
                    {
                        sAFAdmin = "(" + sAFAdmin + " and " + sCustodianFilter + ") ";
                    }
                    else
                    {
                        sAFAdmin = "(" + sCustodianFilter + ") ";
                    }
                }
                else
                {
                    //if (QuickSearchSQL.Trim() == "")  // if no search exists show all no owner records
                    //{
                    if (sAFAdmin.Trim() != "")
                    {
                        sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                    }
                    else
                    {
                        sAFAdmin = "(" + sCustodianFilter + ") ";
                    }
                    //sAFAdmin += " " + sCustodianFilter;
                    // }
                }



            objSec = null;

            string strSelectFlds = GetSelectFlds(dtaPage, dtaPageSrch, ref hsDatatype);
            if (strSelectFlds != "")
            {
                string strKeyValues = GetKeyValues(dtaPage, dtaPageSrch, dtaPageKeys);
                //string strModifiedFields = GetModifiedFields(ref dtaPage, ref dtPageControls);
                string strJoins = GetJoins(dtaPage, dtaPageSrch, dtaPageKeys);

                if (strKeyValues != "")
                    strPageSql = "select " + strKeyValues + " keys, " + strSelectFlds + " from " + strTableNames + "";//strPageSql = "select " + strSelectFlds + ", " + strKeyValues + " keys from " + strTableNames + "";
                else
                    strPageSql = "select " + strSelectFlds + " from " + strTableNames + "";

                if (childField.Length > 0)
                    if (HttpContext.Current.Request["PK"] != null)
                        strJoins += childField + "='" + HttpContext.Current.Request["PK"].ToString() + "'";



                if (strJoins != "")
                {
                    strPageSql += " where " + strJoins;
                }
                else
                {
                    if (sAFAdmin != "") //modified by srivatsan
                    {
                        strPageSql += " where " + sAFAdmin;
                    }
                    else
                    {
                        strPageSql += " where 1=1 ";
                    }
                }


              strPageSql = GetNotesParameter(strPageSql,dtaPageSrch); // Added by srivatsan
              strPageSql = GetDocumentsParameter(strPageSql, dtaPageSrch); // Added by 'Imran Gani' on Sep 18 2012 for Documents changes
                //if (strModifiedFields != "") strPageSql = strPageSql.TrimEnd()+  " order by " + strModifiedFields;
              strPageSql = GetTaskParameter(strPageSql, dtaPageSrch); // Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts
            }
        }

        return strPageSql;
    }
    public string GetModifiedFields(ref DataTable dtaPage, ref DataTable dtPageControls)
    {
        //DataRow[] dr = dtPageControls.Select("control_attrib_id='modified_at'");
        try
        {
            if (dtPageControls.Select("control_attrib_id='modified_at'").Length > 0)
                return "[" + dtaPage.Rows[0]["page_id"].ToString() + "].[" + "modified_at" + "] desc";
            else
                if (dtPageControls.Select("control_attrib_id='modified_date'").Length > 0)
                    return "[" + dtaPage.Rows[0]["page_id"].ToString() + "].[" + "modified_date" + "] desc";
        }
        catch (Exception e)
        {
        }
        return "";
    }
    private string getObject_af_row_id(string Object_id)
    {
        HDD = new HDDatabase();
        return HDD.GetColumnValue("select af_row_id from sy_obj where object_id='" + Object_id + "'");
    }

    public string GetSelectFlds(DataTable dtaPage, DataTable dtaPageSrch, ref Hashtable hsDatatype, ref string sFieldAliases, ref DataTable dtPageControls, ref string CombinerOrderByField, ref string OrderBy)
    {
        BindControl BC = new BindControl();
        HDD = new HDDatabase();
        HDS = new security();
        string strSelectFlds = "";
        string strPageId = "";
        string strTableName = "";
        string strSearchAttribName = "";
        string sObject_id = "";
        string sObject_af_row_id = "";
        for (int i = 0; i < dtaPage.Rows.Count; i++)
        {
            strPageId = dtaPage.Rows[i]["page_id"].ToString();
            strTableName = dtaPage.Rows[i]["page_table_name"].ToString();
            sObject_id = dtaPage.Rows[i]["object_id"].ToString();
            sObject_af_row_id = CommonFunctions.GetColValueFromPageInfo((HttpContext.Current.Request.QueryString["pgs_id"] == null ? "" : HttpContext.Current.Request.QueryString["pgs_id"].ToString()), "sy_obj", "af_row_id", "object_id='" + sObject_id + "'");
            if (sObject_af_row_id == "") sObject_af_row_id = getObject_af_row_id(sObject_id);
            if (!HDS.getObjectRightsForUser(sObject_id, "read"))
                continue;

            DataRow[] droPageSrch = dtaPageSrch.Select("page_id='" + strPageId.Replace("'", "''") + "' and list_flag=1", "search_seq");
            for (int j = 0; j < droPageSrch.Length; j++)
            {
                strSearchAttribName = droPageSrch[j]["search_attrib_name"].ToString();
                if (strSearchAttribName == "")
                {
                    strSearchAttribName = droPageSrch[j]["search_attrib_id"].ToString();
                }
                if (strSelectFlds != "")
                {
                    strSelectFlds += ", ";
                }
                if (sFieldAliases != "")
                {
                    sFieldAliases += ", ";
                }
                /*
                * #REVISIT# added code here to include bind value, need to replace this with good logic
                * as this will be degrade performance very much
                */
                string strBindRowID = droPageSrch[j]["control_bind_id"].ToString();
                strSelectFlds += "[" + strPageId + "].[" + droPageSrch[j]["search_attrib_id"].ToString() + "] as [" + strSearchAttribName + "]";
                sFieldAliases += "[" + strSearchAttribName + "]";
                if (OrderBy.TrimStart('[').TrimEnd(']') == strSearchAttribName) // Added by 'Imran Gani' on 14-Mar-2014, to get real field id for sroting.
                    OrderBy = "[" + strPageId + "].[" + droPageSrch[j]["search_attrib_id"].ToString() + "]";
                if (j == 0)
                {
                    CombinerOrderByField = "[" + strSearchAttribName + "]";
                }
                if (!hsDatatype.Contains(strSearchAttribName))
                    hsDatatype.Add(strSearchAttribName, droPageSrch[j]["control_attrib_type"].ToString());
            }
            string sOrderby = "modified_at";
            if (dtPageControls.Select("control_attrib_id='modified_at'").Length > 0)
                sOrderby = "modified_at";
            else
                if (dtPageControls.Select("control_attrib_id='modified_date'").Length > 0)
                    sOrderby = "modified_date";
            strSelectFlds += ", [" + strPageId + "].[" + sOrderby + "]";
        }
        return strSelectFlds;
    }

    public string GetSelectFlds(DataTable dtaPage, DataTable dtaPageSrch, ref Hashtable hsDatatype)
    {
        BindControl BC = new BindControl();
        string strSelectFlds = "";
        string strPageId = "";
        string strTableName = "";
        string strSearchAttribName = "";
        string sObject_id = "";
        string sObject_af_row_id = "";
        for (int i = 0; i < dtaPage.Rows.Count; i++)
        {
            strPageId = dtaPage.Rows[i]["page_id"].ToString();
            strTableName = dtaPage.Rows[i]["page_table_name"].ToString();
            sObject_id = dtaPage.Rows[i]["object_id"].ToString();
            sObject_af_row_id = getObject_af_row_id(sObject_id);
            if (!HDS.getObjectRightsForUser(sObject_id, "read"))
                continue;

            DataRow[] droPageSrch = dtaPageSrch.Select("page_id='" + strPageId.Replace("'", "''") + "' and list_flag=1", "search_seq");
            for (int j = 0; j < droPageSrch.Length; j++)
            {
                strSearchAttribName = droPageSrch[j]["search_attrib_name"].ToString();
                if (strSearchAttribName == "")
                {
                    strSearchAttribName = droPageSrch[j]["search_attrib_id"].ToString();
                }
                if (strSelectFlds != "")
                {
                    strSelectFlds += ", ";
                }
                /*
                * #REVISIT# added code here to include bind value, need to replace this with good logic
                * as this will be degrade performance very much
                */
                string strBindRowID = droPageSrch[j]["control_bind_id"].ToString();
                /*if (strBindRowID == "")
                {*/
                strSelectFlds += "[" + strPageId + "].[" + droPageSrch[j]["search_attrib_id"].ToString() + "] as [" + strSearchAttribName + "]";
                if (!hsDatatype.Contains(strSearchAttribName))
                    hsDatatype.Add(strSearchAttribName, droPageSrch[j]["control_attrib_type"].ToString());
                /*}
                else
                {
                    strSelectFlds += "(" + BC.GetBindSql_forValue(strBindRowID) + " [" + strPageId + "].[" + droPageSrch[j]["search_attrib_id"].ToString() + "]) as [" + strSearchAttribName + "]";
                    if (!hsDatatype.Contains(strSearchAttribName))
                        hsDatatype.Add(strSearchAttribName, droPageSrch[j]["control_attrib_type"].ToString());
                }*/
            }
        }
        return strSelectFlds;
    }

    public string GetJoins(DataTable dtaPage, DataTable dtaPageSrch, DataTable dtaPageKeys)
    {
        string strJoins = "";
        string strPageId = "";
        string strPrevPageId = "";
        string strPageKey = "";
        if (HttpContext.Current.Request["PK"] != null)
        {
            for (int i = 0; i < dtaPage.Rows.Count; i++)
            {
                strPrevPageId = strPageId;
                strPageId = dtaPage.Rows[i]["page_id"].ToString();
                //if (i > 0)
                //{
                DataRow[] droPageSrch = dtaPageSrch.Select("page_id='" + strPageId.Replace("'", "''") + "'");
                //If page search does not exits, joins need not added with select sql
                if (droPageSrch.Length > 0)
                {
                    DataRow[] droPageKeys = dtaPageKeys.Select("af_row_id='" + droPageSrch[0]["af_row_id2"].ToString() + "'");//, "page_key_seq");
                    //DataRow[] droPageKeys = dtaPageKeys.Select("page_id='" + strPageId.Replace("'", "''") + "'");//, "page_key_seq");
                    for (int j = 0; j < droPageKeys.Length; j++)
                    {
                        strPageKey = droPageKeys[j]["attrib_id"].ToString();
                        //if (IsPrevPageKey(strPrevPageId, strPageKey, dtaPageKeys))
                        //{
                        if (strJoins != "")
                        {
                            strJoins += " and ";
                        }
                        strJoins += "[" + strPageId.Replace("'", "''") + "].[" + strPageKey + "] = '" + HttpContext.Current.Request["PK"].ToString() + "'";
                        //}
                    }
                }
                //}
            }
        }
        return strJoins;
    }

    private bool IsPrevPageKey(string strPageId, string strKey, DataTable dtaPageKeys)
    {
        bool blnStatus = false;
        DataRow[] droPageKey = dtaPageKeys.Select("page_id='" + strPageId.Replace("'", "''") + "'");//, "page_key_seq");
        for (int i = 0; i < droPageKey.Length; i++)
        {
            if (strKey.ToLower() == droPageKey[i]["page_key"].ToString().ToLower())
            {
                blnStatus = true;
                i = droPageKey.Length;
            }
        }
        return blnStatus;
    }

    public string GetTableNames(DataTable dtaPage, DataTable dtaPageSrch)
    {
        string strTableNames = "";
        string strPageTblName = "";
        string strPageId = "";
        //string sAF_ROW_ID = "";
        for (int i = 0; i < dtaPage.Rows.Count; i++)
        {
            strPageId = dtaPage.Rows[i]["page_id"].ToString();
            //sAF_ROW_ID = dtaPage.Rows[i]["af_row_id"].ToString();

            DataRow[] droPageSrch = dtaPageSrch.Select("page_id='" + strPageId.Replace("'", "''") + "'");
            //DataRow[] droPageSrch = dtaPageSrch.Select("af_row_id='" + sAF_ROW_ID + "'");
            if (droPageSrch.Length > 0)
            {
                strPageTblName = dtaPage.Rows[i]["page_table_name"].ToString();

                if (strTableNames != "")
                {
                    strTableNames += ", ";
                }
                strTableNames += " [" + strPageTblName + "] [" + strPageId + "]";
            }
        }
        return strTableNames;
    }

    public string GetKeyValues(DataTable dtaPage, DataTable dtaPageSrch, DataTable dtaPageKeys)
    {
        string strKeyValuesRet = "";
        string strPageKeys = "";
        string strPageId = "";
        string strKey = "";
        for (int i = 0; i < dtaPage.Rows.Count; i++)
        {
            strPageId = dtaPage.Rows[i]["page_id"].ToString();
            DataRow[] droPageSrch = dtaPageSrch.Select("page_id='" + strPageId.Replace("'", "''") + "'");
            strPageKeys = "";
            //if (droPageSrch.Length > 0)
            //{
            //DataRow[] droPageKeys = dtaPageKeys.Select("page_id='" + strPageId.Replace("'", "''") + "'", "page_key_seq");
            //DataRow[] droPageKeys = dtaPageKeys.Select("page_id='" + dtaPage.Rows[i]["af_row_id"].ToString() + "'");//, "page_key_seq");
            //DataRow[] droPageKeys = dtaPageKeys.Select("af_row_id='" + dtaPageSrch.Rows[i]["af_row_id2"].ToString() + "'");//, "page_key_seq");

            //if (droPageKeys.Length > 0)
            //{
            //    for (int j = 0; j < droPageKeys.Length; j++)
            //    {
            //        strKey = droPageKeys[j]["attrib_id"].ToString();
            //        if (strPageKeys != "")
            //        {
            //            strPageKeys += " + '~' + ";
            //        }
            //        strPageKeys += "[" + strPageId + "].[" + strKey + "]";
            //    }
            //}
            //else
            strPageKeys += "[" + strPageId + "].[af_row_id]";
            //}
            if (strPageKeys != "")
            {
                if (strKeyValuesRet != "")
                {
                    strKeyValuesRet += "+ '|' + ";
                }
                strKeyValuesRet += strPageKeys;
            }
        }
        return strKeyValuesRet;
    }

    private void getQuickSearchData(ref DropDownList ddl, string SQL, DataRow PageSearch)
    {
        HDD = new HDDatabase();
        string sDataType = PageSearch["control_attrib_type"].ToString().ToLower();
        string sValue = "";
        string sStoragevalue = "";
        string strBindRowID = PageSearch["control_bind_id"].ToString();
        DataTable dtValues = new DataTable();
        // Added by srivatsan on June 15 2009 for owner id field
        if (PageSearch["search_attrib_id"].ToString() == "created_by" || PageSearch["search_attrib_id"].ToString() == "modified_by" || PageSearch["search_attrib_id"].ToString().ToLower() == "owner_id" || HttpContext.Current.Request["pgs_id"].ToString() == "6421de320e189de8")//added for system fields in quick search // Modified by'Imran Gani' on 25-Jan-2013, to include the check for report pageset.
            dtValues = HDD.GetDataTable(SQL, false, true).Copy();
        else
            dtValues = HDD.GetDataTable(SQL, true, true).Copy();
        // dtValues = HDD.GetDataTable(SQL, false, true).Copy();

        //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
        //CommonFunctions.decodeData(dtValues);
        string sBindStoreField = "", sBindDisplayField = "", sBindTable = "";
        DataRow drBind = null;
        if (strBindRowID != "")
            drBind = HDD.GetTableRow("select * from sy_bnd where af_row_id = '" + strBindRowID + "';");
        if (drBind != null)
        {
            sBindStoreField = drBind["bind_value"].ToString();
            sBindDisplayField = drBind["bind_text"].ToString();
            sBindTable = drBind["bind_table"].ToString();

            //if (sBindStoreField.ToLower() == "af_row_id") //Commented by srivatsan
            getQuickSrchAFROWID(ref dtValues, sBindTable, sBindDisplayField, sBindStoreField);
        }

        ddl.Items.Add(GlobalValues.ShowAll);
        Localization li = new Localization();
        //string sDTFormat = li.getDateTimeFormat(); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        //string sDFormat = li.getDateFormat(); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        string sDTFormat = MBLocalization.getDateTimeFormat(HttpContext.Current.Session["userlocale"].ToString());
        string sDFormat = MBLocalization.getDateFormat(HttpContext.Current.Session["userlocale"].ToString());
        foreach (DataRow dr1 in dtValues.Rows)
        {
            sValue = dr1[0].ToString();
            if (strBindRowID != "")
            {
                sStoragevalue = dr1[1].ToString();
            }
            if (sValue != "")
            {
                #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
                //if (sDataType == "dt")
                //{
                //    if (sValue != "")
                //    {
                //        sValue = li.getDateTime4TimeZone(sValue, sUTC_Offset, false, false);
                //        //DateTime dtUser = new DateTime();
                //        //dtUser = DateTime.Parse(sValue);
                //        //sValue = dtUser.ToString(sDTFormat);
                //    }
                //}
                //else if (sDataType == "cu")
                //    sValue = DDI.manageCurrency(sValue, currencyCode_Rate);
                //else if (sDataType == "da")
                //{
                //    DateTime dtDate = new DateTime();
                //    dtDate = DateTime.Parse(sValue);
                //    sValue = dtDate.ToString(sDFormat);
                //}
                #endregion

                #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
                switch (sDataType)
                {
                    case "dt":
                        sValue = li.getDateTime4TimeZone(sValue, sUTC_Offset, false, false);
                        break;
                    case "da":
                        DateTime dtDate = new DateTime();
                        dtDate = DateTime.Parse(sValue);
                        sValue = dtDate.ToString(sDFormat);
                        break;
                    case "cu":
                        sValue = DDI.manageCurrency(sValue, currencyCode_Rate);
                        break;
                    case "nu":
                    case "an":
                        sValue = MBLocalization.getLocalizedInteger(HttpContext.Current.Session["userlocale"].ToString(), int.Parse(sValue));
                        break;
                    case "dc":
                    case "fl":
                        sValue = MBLocalization.getLocalizedDecimal(HttpContext.Current.Session["userlocale"].ToString(), double.Parse(sValue));
                        break;
                }
                #endregion
            }
            if (ddl.Items.FindByText(sValue) == null)
            {
                ListItem item;
                if (strBindRowID != "")
                {
                    item = new ListItem(sValue, sStoragevalue);
                }
                else
                {
                    item = new ListItem(sValue, sValue);
                }
                ddl.Items.Add(item);
                //ddl.Items.Add(sValue);
            }
        }
        li = null;
        //foreach (DataRow dr1 in dtValues.Rows)
        //{
        //    sValue = dr1[0].ToString();
        //    if (sValue != "")
        //    {
        //        if (sDataType == "dt")
        //        {
        //            if (sValue != "")
        //                sValue = DDI.getUsersDT(sValue, sUTC_Offset);
        //        }
        //        else if (sDataType == "cu")
        //            sValue = DDI.manageCurrency(sValue, currencyCode_Rate);
        //        else if (sDataType == "da")
        //            if (sValue.IndexOf(" ") != -1)
        //                sValue = DateTime.Parse(sValue.Substring(0, sValue.IndexOf(" "))).ToString("dd-MMM-yyyy"); ;
        //    }
        //    //if (strBindRowID != "" && sBindStoreField.ToLower() == "af_row_id")
        //    //{
        //    //    string strtext1 = getQStext(strBindRowID, dr1);
        //    //    string strvalue1 = getQSvalues(strBindRowID, dr1);

        //    //    ddl.Items.Add(new ListItem(strtext1, strvalue1));//Implemented by Prithi on 12-Nov-2008
        //    //}
        //    //else
        //    //{
        //    if (ddl.Items.FindByText(sValue) == null)
        //        ddl.Items.Add(sValue);
        //    //}
        //}
        dtValues = null;
        //dtValuesNew = null;
    }
    private string getQStext(string strBindRowID, DataRow dr)//Implemented by Prithi on 12-Nov-2008,to retrieve the text
    {
        string strsql = "select bind_value,bind_text,bind_table from sy_bnd where af_row_id = '" + strBindRowID + "';";
        string strvalue, strtext, ssql, strtext1 = "";
        DataTable dtbnd = new DataTable();

        dtbnd = HDD.GetDataTable(strsql);
        for (int k = 0; k < dtbnd.Rows.Count; k++)
        {
            strvalue = dtbnd.Rows[k]["bind_value"].ToString();
            if (strvalue.Contains("af_row_id"))
            {
                strtext = dtbnd.Rows[k]["bind_text"].ToString();
                string strtab = dtbnd.Rows[k]["bind_table"].ToString();
                DataTable strtb = new DataTable();
                ssql = "select " + strtext + "," + strvalue + " from " + strtab + "";
                DataTable dt = new DataTable();
                dt = HDD.GetDataTable(ssql, true).Copy();
                if (dr[0].ToString() == "")
                {
                    strtext1 = " ";
                }
                else
                {
                    DataRow[] dx = dt.Select("af_row_id= '" + dr[0].ToString() + "'");
                    if (dx.Length == 0)
                    {
                        strtext1 = "Record Not Found";
                    }
                    else
                    {
                        for (int l = 0; l < dx.Length; l++)
                        {
                            strtext1 = dx[l][strtext].ToString();

                        }
                    }
                }
            }
        }

        return strtext1;
    }
    private string getQSvalues(string strBindRowID, DataRow dr) //Implemented by Prithi on 12-Nov-2008 , to get the af_row_id values
    {

        string strsql = "select bind_value,bind_text,bind_table from sy_bnd where af_row_id = '" + strBindRowID + "';";
        string strvalue, strtext, ssql, value = "";
        DataTable dtbnd = new DataTable();

        dtbnd = HDD.GetDataTable(strsql);
        for (int k = 0; k < dtbnd.Rows.Count; k++)
        {
            strvalue = dtbnd.Rows[k]["bind_value"].ToString();
            if (strvalue.Contains("af_row_id"))
            {
                strtext = dtbnd.Rows[k]["bind_text"].ToString();
                string strtab = dtbnd.Rows[k]["bind_table"].ToString();
                DataTable strtb = new DataTable();
                ssql = "select " + strtext + "," + strvalue + " from " + strtab + "";
                DataTable dt = new DataTable();
                dt = HDD.GetDataTable(ssql, true).Copy();
                DataRow[] dx = dt.Select("af_row_id= '" + dr[0].ToString() + "'");
                for (int l = 0; l < dx.Length; l++)
                {
                    value = dx[l][strvalue].ToString();

                }
            }
            else
                value = strvalue;
        }

        return value;
    }

    private void getQuickSrchAFROWID(ref DataTable dtValues, string Bind_Table, string Display_Field, string Storage_Field)
    {
        DataTable dt = new DataTable();
        try
        {
            //dt = HDD.GetDataTable("select * from " + Bind_Table);
            dtValues.Columns.Add("storage_value");
            dt = HDD.GetDataTable("select " + Storage_Field + "," + Display_Field + " from " + Bind_Table + "");
            foreach (DataRow dr in dtValues.Rows)
            {
                DataRow[] drr = dt.Select(Storage_Field + " = '" + dr[0].ToString().Replace("'", "''") + "'");
                if (drr.Length > 0)
                {
                    try
                    {
                        dr[0] = drr[0][Display_Field].ToString();
                    }
                    catch
                    {
                        dr[0] = drr[0][1].ToString();
                    }
                    dr[1] = drr[0][Storage_Field].ToString();
                }
            }

            dtValues.AcceptChanges();

            DataRow[] drrTemp = dtValues.Select("", "quick_search asc");
            dt = dtValues.Copy();
            dt.Rows.Clear();
            foreach (DataRow drTemp in drrTemp)
            {
                dt.ImportRow(drTemp);
            }
            dtValues = dt;
        }
        catch (Exception Ex)
        {
            LogWriter.WriteLog("getQuickSrchAFROWID : Error : " + Ex.Message);
        }
        //return dt;
    }

    public bool BuildQuickSearch(DataTable dtaPage, DataTable dtaPageSrch, string strPagesetRowId, HtmlForm frmObj)
    {
        HDS = new security();
        HDDatabase hdd = new HDDatabase();
        DataRow[] dr_PageQuickSrch = dtaPageSrch.Select("quick_search=1", "search_seq");
        //PlaceHolder ph_QS = (PlaceHolder)frmObj.FindControl("ContentPlaceHolder3").FindControl("ph_quick_search");//PlaceHolder ph_QS = (PlaceHolder)frmObj.FindControl("ph_quick_search");
        PlaceHolder ph_QS = (PlaceHolder)DDI.FindControl(frmObj.Controls, "ph_quick_search");//PlaceHolder ph_QS = (PlaceHolder)frmObj.FindControl("ph_quick_search");
        ph_QS.Visible = true;
        for (int j = 0; j < dr_PageQuickSrch.Length; j++)
        {
            DataRow[] droPageTable = dtaPage.Select("page_id='" + dr_PageQuickSrch[j]["page_id"].ToString().Replace("'", "''") + "'");

            if (!HDS.getObjectRightsForUser(droPageTable[0]["object_id"].ToString(), "read"))
                continue;

            string strTableName = droPageTable[0]["page_table_name"].ToString();
            string strAttribId = dr_PageQuickSrch[j]["search_attrib_id"].ToString();
            string strPageId = dr_PageQuickSrch[j]["page_id"].ToString();
            string strBindRowID = dr_PageQuickSrch[j]["control_bind_id"].ToString();
            //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
            string modelConString = "";
            //string page_id = hdd.GetColumnValue("select page_id from sy_pg where object_id='" + dsReport.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString() + "'");
            modelConString = HttpContext.Current.Session["servercon"].ToString();
            string str_OwnerId = "";
            string str_BusinessUnit = "";
            if (HttpContext.Current.Session["dbcon"].ToString() != modelConString)
            {
                BusinessUnit.Access ACS = new BusinessUnit.Access(HttpContext.Current.Session["userid"].ToString(), hdd.GetConnection().ConnectionString, dr_PageQuickSrch[j]["page_id"].ToString().Replace("'", "''"));
                str_OwnerId = ACS.AccessableOwners;
                str_BusinessUnit = ACS.AccessableBuUnits;
            }
            //----------------End for Org Security------------------
            Label lb = new Label();
            lb.ID = strAttribId;
            lb.Text = HttpUtility.HtmlEncode(dr_PageQuickSrch[j]["search_attrib_name"].ToString()) + ":";
            lb.CssClass = "pgForm_fld_text";
            if (lb.Text == ":")
            {
                lb.Text = dr_PageQuickSrch[j]["search_attrib_id"].ToString() + ":";
            }
            ph_QS.Controls.Add(new LiteralControl("<tr><td>"));
            //ph_QS.Controls.Add(new LiteralControl("<td>"));
            ph_QS.Controls.Add(lb);
            ph_QS.Controls.Add(new LiteralControl("</td>"));

            string strSQL = "";
            // Added by srivatsan on June 15 2009 for owner id field
            if (strAttribId.ToLower() == "created_by" || strAttribId.ToLower() == "modified_by" || strAttribId.ToLower() == "owner_id")//added for system fields in quick search
            {
                string sUserDisplayName = getUserDisplayName();
                if (HttpContext.Current.Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
                    strSQL = "select distinct(" + sUserDisplayName + ") as Quick_Search from sy_usr inner join [" + strTableName + "] on sy_usr.af_row_id=[" + strTableName + "].[" + strAttribId + "]";// where sy_usr.af_row_id<>'e51e0327224a2eb9'//strSQL = "select distinct(user_id) as Quick_Search from sy_usr inner join [" + strTableName + "] on sy_usr.af_row_id=[" + strTableName + "].[" + strAttribId + "]";// where sy_usr.af_row_id<>'e51e0327224a2eb9'
                else
                    strSQL = "select distinct(" + sUserDisplayName + ") as Quick_Search from sy_usr inner join [" + strTableName + "] on sy_usr.af_row_id=[" + strTableName + "].[" + strAttribId + "] where sy_usr.af_row_id<>'e51e0327224a2eb9'";//strSQL = "select distinct(user_id) as Quick_Search from sy_usr inner join [" + strTableName + "] on sy_usr.af_row_id=[" + strTableName + "].[" + strAttribId + "] where sy_usr.af_row_id<>'e51e0327224a2eb9'";
            }
            else
            {
                // Lines commented by 'Imran Gani' on 28-Jun-2013, to handle Org security for report with report access.
                //if (strPagesetRowId == "ps_report") // Added by 'Imran Gani' on 25-Jan-2013, for report security per role.
                //{
                //    SecurityFilter objSec = new SecurityFilter();
                //    string sAFAdmin = objSec.QueryForAFAdmin();
                //    string sCustodianFilter = objSec.QueryForCustodianFilter();
                //    if (sCustodianFilter.Trim() != "")
                //        if (!sCustodianFilter.StartsWith("or"))
                //        {
                //            if (sAFAdmin.Trim() != "")
                //                sAFAdmin = "(" + sAFAdmin + " and " + sCustodianFilter + ") ";
                //            else
                //                sAFAdmin = "(" + sCustodianFilter + ") ";
                //        }
                //        else
                //        {
                //            if (sAFAdmin.Trim() != "")
                //                sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                //            else
                //                sAFAdmin = "(" + sCustodianFilter + ") ";
                //        }
                //    strSQL = "Select distinct [" + strAttribId + "] as Quick_Search from [" + strTableName + "] where " + sAFAdmin + " or [af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 )";
                //}
                //else
                    strSQL = "Select distinct [" + strAttribId + "] as Quick_Search from [" + strTableName + "] ";//where [" + strAttribId + "] <>''";
            }
            string sRowLevel = HDS.GridRowLevelSecuritySqlForQuickSearch(dtaPage);
            if (sRowLevel != "")
                //strSQL = strSQL + sRowLevel;
                strSQL = strSQL + " where 1 = 1 " + sRowLevel;
            // Added by srivatsan on June 15 2009 for owner id field
            //-----------Modified by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
            if (strAttribId.ToLower() == "created_by" || strAttribId.ToLower() == "modified_by" || strAttribId.ToLower() == "owner_id")//added for system fields in quick search
            {
                if (str_OwnerId != "")
                {
                    if (strSQL.Contains("where") == true)
                        strSQL += " " + str_OwnerId + " or owner_id is null ";
                    else
                        strSQL += " where " + str_OwnerId.Remove(0, 5) + " or owner_id is null ";
                    if (strPagesetRowId == "6421de320e189de8") // Added by 'Imran Gani' on 28-Jun-2013, to handle Org security for report with report access.
                        strSQL += " or [af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 ) ";
                }
                strSQL = strSQL + " order by Quick_Search";
            }
            else
            {
                if (str_OwnerId != "")
                {
                    if (strSQL.Contains("where") == true)
                        strSQL += " " + str_OwnerId + " or owner_id is null ";
                    else
                        strSQL += " where " + str_OwnerId.Remove(0, 5) + " or owner_id is null ";
                    if (strPagesetRowId == "6421de320e189de8") // Added by 'Imran Gani' on 28-Jun-2013, to handle Org security for report with report access.
                        strSQL += " or [af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 ) ";
                }
                strSQL = strSQL + " order by [" + strAttribId + "] asc";
            }
            //----------------End for Org Security------------------
            DropDownList ddl = new DropDownList();
            ddl.ID = "Quick_Search_" + strPageId + "_" + strAttribId;
            getQuickSearchData(ref ddl, strSQL, dr_PageQuickSrch[j]);
            ddl.DataTextField = "Quick_Search";
            ddl.CssClass = "controlFont";//by sanal on Feb 09, 2011
            ddl.Style.Add("vertical-align", "middle");
            ddl.Style.Add("height", "21px");
            ddl.Attributes.Add("onchange", "javascript:mb_updateGoButton();");
            if (strBindRowID != "") //changed by Prithi on 11-Nov-2008
            {
                ddl.DataValueField = "val";
            }
            else
            {
                ddl.DataValueField = "Quick_Search";
            }
            ddl.DataBind();
            //ddl.Font.Name = "Arial";
            //ddl.Font.Size = FontUnit.Parse("10pt"); ;
            if (!frmObj.Page.IsPostBack)
            {
                ddl.SelectedValue = GlobalValues.ShowAll;
                ddl.SelectedValue = getValueInBothGetandPost(ref frmObj, strPageId, strAttribId);
            }
            //ddl.Attributes.Add("OnChange", "submitform()"); // Commented by srivatsan on July 27 2009 for Filter Changes
            ph_QS.Controls.Add(new LiteralControl("<td align=left valign='middle'>"));
            ph_QS.Controls.Add(ddl);
            if (j == dr_PageQuickSrch.Length - 1) // Add Go button to the last drop down
            {
                AddGoButton(ref ph_QS, dtaPageSrch);
            }
            ph_QS.Controls.Add(new LiteralControl("</td></tr>"));
            //ph_QS.Controls.Add(new LiteralControl("</tr>"));
            //ph_QS.Controls.Add(new LiteralControl("<br>"));


        }
        if (ph_QS.Controls.Count > 0)
        {
            //ph_QS.Controls.AddAt(0, new LiteralControl("<tr class='Grid_Header'><td colspan='2'>&nbsp;<img src='Images/filter.gif' alt='filter' align='middle' />&nbsp;Filter...</td></tr>"));
            ph_QS.Controls.AddAt(0, new LiteralControl("<tr class='Grid_Header'><td colspan='2'><table cellpadding='0' cellspacing='0' width='100%'><tr class='Grid_Header' style='height:20px;'><td width='20px'>&nbsp;<img src='Images/filter.gif' alt='filter' /></td><td valign='middle'>&nbsp;Filter...</td></tr></table></td></tr>"));
        }
        return true;
    }
    public string PagesetObjectSearchSql(ref DataTable dtaPageSearch, ref DataTable dtaPageControls,ref DataTable dtaPage, HtmlForm frmObj,ref HDDatabase hdCompany)
    {
        string searchString = "";
        bool performObjectSearch = true; 
        
        
        HiddenField hfObjectSearch = (HiddenField)frmObj.FindControl("ctl00$ContentPlaceHolder3$hfObjectSearch");
        if (hfObjectSearch != null)
        {
            performObjectSearch = hfObjectSearch.Value.ToString() == "search";
        }
        if (!performObjectSearch) return "";
        TextBox txtObjectSearch = (TextBox)frmObj.FindControl("ctl00$ContentPlaceHolder3$txtObjectSearch");
        if (txtObjectSearch != null)
        {
            searchString = txtObjectSearch.Text;
        }
        if (searchString == "") return "";

        // Added by 'Imran Gani' on 11-Mar-2013, to get search SQL through below function
        string strObjectSearchSql = getObjectSearchSQL(dtaPageSearch, dtaPageControls, dtaPage, searchString);

        if (strObjectSearchSql.Length > 0)
        {
            LinkButton lnk = (LinkButton)frmObj.FindControl("ctl00$ContentPlaceHolder3$lnkBtnViewAll");
            if (lnk != null)
            {
                lnk.Visible = true;
                Button btn = (Button)frmObj.FindControl("ctl00$ContentPlaceHolder3$btnfilter");
                if (btn != null)
                {
                    btn.Visible = false;
                }
                PlaceHolder ph_QS = (PlaceHolder)DDI.FindControl(frmObj.Controls, "ph_quick_search");
                ph_QS.Visible = false;
                Label lblListHeader = (Label)frmObj.FindControl("ctl00$ContentPlaceHolder3$lblListHeader");
                //HtmlEncode added by Sampath on 17-Nov-2011 for IPP Tech check 
                lblListHeader.Text = "Search results for <b>\"" + HttpUtility.HtmlEncode(searchString) + "\"</b>";
            }
        }

        #region Old coding to get search SQL Command by 'Imran Gani' on 11-Mar-2013

        /* Command by 'Imran Gani' on 11-Mar-2013, to call search string through getObjectSearchSQL function

        //return "";
       //DataRow[] drPageSearchs = dtaPageSearch.Select("list_flag=1", "search_seq"); //Changes Made By Dhanapal On Dec 14 2010
        DataRow[] drPageSearchs ;
        bool interruptloop = false; //Added by Dhanapal On Dec 15 2010
        bool isbind = false; //Added By Dhanapal On Dec 15 2010
        drPageSearchs = dtaPageControls.Select("is_search=1", "control_seq");

        if (drPageSearchs == null || drPageSearchs.Length < 1)
        {
        //drPageSearchs = dtaPageControls.Select("control_visible=1", "control_seq");
         drPageSearchs = dtaPageSearch.Select("list_flag=1", "search_seq");
         interruptloop = true;
        }
        
        string strObjectSearchSql = " ";

        for (int j = 0; j < drPageSearchs.Length; j++)
        {
           // string strAttribId = drPageSearchs[j]["control_attrib_id"].ToString();
           string strAttribId = drPageSearchs[j]["control_id"].ToString();
            //string strPageId = drPageSearchs[j]["page_id"].ToString(); 
            //dtaPage.Select("af_row_id='" + drPageSearchs[j]["page_id"].ToString() + "'")[0]["page_id"].ToString();
           string strPageId = "";
            if (interruptloop) //This is for default Column if no is_search is selected
           {
                strPageId = dtaPage.Select("page_id='" + drPageSearchs[j]["page_id"].ToString() + "'")[0]["page_id"].ToString();
           }
           else //This is condition Executes if is_Search is enabled for any field
           {
                strPageId = dtaPage.Select("af_row_id='" + drPageSearchs[j]["page_id"].ToString() + "'")[0]["page_id"].ToString();
           }
            string strBindRowID = drPageSearchs[j]["control_bind_id"].ToString();
            string strControlAttribType = drPageSearchs[j]["control_attrib_type"].ToString();
            string strObjectSearchValue = searchString;

           if (searchString!="")
            {
                string sBindStoreField = "";
                string sValues = "";
                 if (strBindRowID != "") 
                 {
                     DataRow drBind = hdCompany.GetTableRow("select * from sy_bnd where af_row_id = '" + strBindRowID + "';");
                     string sBindDisplayField = "", sBindTable = "";

                     if (drBind != null)
                     {
                         sBindStoreField = drBind["bind_value"].ToString();
                         sBindDisplayField = drBind["bind_text"].ToString();
                         sBindTable = drBind["bind_table"].ToString();

                         DataTable dtBind = hdCompany.GetDataTable("select " + sBindStoreField + " from " + sBindTable + " where " + sBindDisplayField + " like '%" + strObjectSearchValue.Replace("'", "''") + "%'"); // Modified by srivatsan on June 04 2009

                         foreach (DataRow dr in dtBind.Rows)
                             sValues = sValues + "'" + dr[sBindStoreField].ToString() + "',";
                         sValues = sValues.TrimEnd(',');
                           if (sValues == "")//Changes Done By Dhanapal On Dec 15 2010 To make sure that BindColumn Presence
                            {
                                 sValues = "''";
                                  //Changes Done By Dhanapal On Dec 15 2010 To make sure that BindColumn Presence
                            }
                           isbind = true;
                     }                    
                 }
                 else
                 {
                    
                 }
                //Commented By Dhanapal On Dec 15 2010

                if (strObjectSearchValue == null)
                {
                    strObjectSearchValue = "";
                }

                //Commented By Dhanapal On Dec 15 2010 to avoid invalid conversion of string to date
                /*if (strControlAttribType.ToLower() == "dt" && strObjectSearchValue != "" && strObjectSearchValue != "--All--")
                {
                    Localization li = new Localization();
                    strObjectSearchValue = li.getDateTime4TimeZone(strObjectSearchValue, sUTC_Offset, true, false);// .getInvariantDateTime(strQuickSearchValue);
                    li = null;
                    //strQuickSearchValue = DDI.getGMT(strQuickSearchValue, sUTC_Offset);
                }
                else if (strControlAttribType.ToLower() == "cu" && strObjectSearchValue != "" && strObjectSearchValue != "--All--")
                    strObjectSearchValue = changeCurrencyToDBValue(strObjectSearchValue, currencyCode_Rate);
                else if (strControlAttribType.ToLower() == "da" && strObjectSearchValue != "" && strObjectSearchValue != "--All--")
                {
                    Localization li1 = new Localization();
                    strObjectSearchValue = li1.getInvariantDate(strObjectSearchValue);
                    li1 = null;
                }

                if (strObjectSearchValue != null && strObjectSearchValue!= "" && strObjectSearchValue != GlobalValues.ShowAll)
                {
                            //if (sBindStoreField.ToLower() == "af_row_id") // Commented by srivatsan
                        if (sValues != "" || isbind)
                            {
                                strObjectSearchSql += " or [" + strPageId + "].[" + strAttribId + "] in (" + sValues + ")";
                                isbind = false;//Change Done By Dhanapal On Dec 15 2010
                            }
                    //else
                    //    strObjectSearchSql += " and 1=2 ";
                    else
                        // Added by srivatsan on June 15 2009 for owner id field
                        if (strAttribId.ToLower() == "created_by" || strAttribId.ToLower() == "modified_by" || strAttribId.ToLower() == "owner_id")
                        {
                            string sUserDisplayName = getUserDisplayName();
                            strObjectSearchSql += " or [" + strPageId + "].[" + strAttribId + "]='" + HDD.GetColumnValue("select af_row_id from sy_usr where " + sUserDisplayName + " like '%" + strObjectSearchValue + "%'") + "'";
                        }
                        else
                            strObjectSearchSql += " or [" + strPageId + "].[" + strAttribId + "] like '%" + strObjectSearchValue.Replace("'", "''") + "%'";
                }

                if (strObjectSearchValue == "")
                {
                    strObjectSearchSql += " or [" + strPageId + "].[" + strAttribId + "] is null";
                }
            }

            if (interruptloop) //Added By Dhanapal For Search if no Is_search Field InActive
            {
                break;
            }
           // break; //Commented By Dhanapal TO Make All Items Search
        }
        
        strObjectSearchSql = strObjectSearchSql.Trim();
        if (strObjectSearchSql != "") //Added By Dhanapal On Dec 15 2010 To Append 'And' keyword and remove the 'OR' Keyword Prefix
        {
            if (strObjectSearchSql.IndexOf("or") !=  -1)
            {
                strObjectSearchSql = strObjectSearchSql.Substring(strObjectSearchSql.IndexOf("or") + 2 , strObjectSearchSql.Length - 2);

                strObjectSearchSql = "  and ( " + strObjectSearchSql + " ) ";
            }
        }
        Command by 'Imran Gani' on 11-Mar-2013, to call search string through getObjectSearchSQL function*/
        #endregion

        return strObjectSearchSql;
    }

    /// <summary>
    /// To get the search conditional query.
    /// </summary>
    /// <param name="dtaPageSearch">Page search data table</param>
    /// <param name="dtaPageControls">Page control data table</param>
    /// <param name="dtaPage">Page details data table</param>
    /// <param name="searchString">search text</param>
    /// <returns>conditional query</returns> // Implemented by 'Imran Gani' on 11-Mar-2013.
    public string getObjectSearchSQL(DataTable dtaPageSearch, DataTable dtaPageControls, DataTable dtaPage, string searchString)
    {
        HDDatabase hdCompany = new HDDatabase();
        DataRow[] drPageSearchs;
        bool interruptloop = false; //Added by Dhanapal On Dec 15 2010
        bool isbind = false; //Added By Dhanapal On Dec 15 2010
        string strObjectSearchSql = "";

        try
        {
            drPageSearchs = dtaPageControls.Select("is_search=1", "control_seq");

            if (drPageSearchs == null || drPageSearchs.Length < 1)
            {
                drPageSearchs = dtaPageSearch.Select("list_flag=1", "search_seq");
                interruptloop = true;
            }

            for (int j = 0; j < drPageSearchs.Length; j++)
            {
                string strAttribId = drPageSearchs[j]["control_id"].ToString();
                string strPageId = "";

                if (interruptloop) //This is for default Column if no is_search is selected
                    strPageId = dtaPage.Select("page_id='" + drPageSearchs[j]["page_id"].ToString() + "'")[0]["page_id"].ToString();
                else //This is condition Executes if is_Search is enabled for any field
                    strPageId = dtaPage.Select("af_row_id='" + drPageSearchs[j]["page_id"].ToString() + "'")[0]["page_id"].ToString();

                string strBindRowID = drPageSearchs[j]["control_bind_id"].ToString();
                string strControlAttribType = drPageSearchs[j]["control_attrib_type"].ToString();
                string strObjectSearchValue = searchString;

                #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
                switch (strControlAttribType.ToLower())
                {
                    case "cu":
                    case "nu":
                    case "an":
                    case "dc":
                    case "fl":
                        strObjectSearchValue = MBLocalization.getNumericValue(HttpContext.Current.Session["userlocale"].ToString(), strObjectSearchValue).ToString();
                        break;
                }
                #endregion

                if (searchString != "")
                {
                    string sBindStoreField = "";
                    string sValues = "";
                    if (strBindRowID != "")
                    {
                        DataRow drBind = hdCompany.GetTableRow("select * from sy_bnd where af_row_id = '" + strBindRowID + "';");
                        string sBindDisplayField = "", sBindTable = "";

                        if (drBind != null)
                        {
                            sBindStoreField = drBind["bind_value"].ToString();
                            sBindDisplayField = drBind["bind_text"].ToString();
                            sBindTable = drBind["bind_table"].ToString();

                            DataTable dtBind = hdCompany.GetDataTable("select " + sBindStoreField + " from " + sBindTable + " where " + sBindDisplayField + " like '%" + strObjectSearchValue.Replace("'", "''") + "%'"); // Modified by srivatsan on June 04 2009

                            foreach (DataRow dr in dtBind.Rows)
                                sValues = sValues + "'" + dr[sBindStoreField].ToString() + "',";
                            sValues = sValues.TrimEnd(',');
                            if (sValues == "")//Changes Done By Dhanapal On Dec 15 2010 To make sure that BindColumn Presence
                                sValues = "''";
                            isbind = true;
                        }
                    }

                    if (strObjectSearchValue == null)
                        strObjectSearchValue = "";

                    //Commented By Dhanapal On Dec 15 2010 to avoid invalid conversion of string to date
                    /*if (strControlAttribType.ToLower() == "dt" && strObjectSearchValue != "" && strObjectSearchValue != "--All--")
                    {
                        Localization li = new Localization();
                        strObjectSearchValue = li.getDateTime4TimeZone(strObjectSearchValue, sUTC_Offset, true, false);// .getInvariantDateTime(strQuickSearchValue);
                        li = null;
                        //strQuickSearchValue = DDI.getGMT(strQuickSearchValue, sUTC_Offset);
                    }
                    else if (strControlAttribType.ToLower() == "cu" && strObjectSearchValue != "" && strObjectSearchValue != "--All--")
                        strObjectSearchValue = changeCurrencyToDBValue(strObjectSearchValue, currencyCode_Rate);
                    else if (strControlAttribType.ToLower() == "da" && strObjectSearchValue != "" && strObjectSearchValue != "--All--")
                    {
                        Localization li1 = new Localization();
                        strObjectSearchValue = li1.getInvariantDate(strObjectSearchValue);
                        li1 = null;
                    }*/

                    if (strObjectSearchValue != null && strObjectSearchValue != "" && strObjectSearchValue != GlobalValues.ShowAll)
                    {
                        if (sValues != "" || isbind)
                        {
                            strObjectSearchSql += " or [" + strPageId + "].[" + strAttribId + "] in (" + sValues + ")";
                            isbind = false;//Change Done By Dhanapal On Dec 15 2010
                        }
                        else
                            // Added by srivatsan on June 15 2009 for owner id field
                            if (strAttribId.ToLower() == "created_by" || strAttribId.ToLower() == "modified_by" || strAttribId.ToLower() == "owner_id")
                            {
                                string sUserDisplayName = getUserDisplayName();
                                strObjectSearchSql += " or [" + strPageId + "].[" + strAttribId + "]='" + HDD.GetColumnValue("select af_row_id from sy_usr where " + sUserDisplayName + " like '%" + strObjectSearchValue + "%'") + "'";
                            }
                            else
                                strObjectSearchSql += " or [" + strPageId + "].[" + strAttribId + "] like '%" + strObjectSearchValue.Replace("'", "''") + "%'";
                    }
                    if (strObjectSearchValue == "")
                        strObjectSearchSql += " or [" + strPageId + "].[" + strAttribId + "] is null";
                }

                if (interruptloop) //Added By Dhanapal For Search if no Is_search Field InActive
                    break;
            }
            strObjectSearchSql = strObjectSearchSql.Trim();
            if (strObjectSearchSql != "") //Added By Dhanapal On Dec 15 2010 To Append 'And' keyword and remove the 'OR' Keyword Prefix
            {
                if (strObjectSearchSql.IndexOf("or") != -1)
                {
                    strObjectSearchSql = strObjectSearchSql.Substring(strObjectSearchSql.IndexOf("or") + 2, strObjectSearchSql.Length - 2);
                    strObjectSearchSql = "  and ( " + strObjectSearchSql + " ) ";
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getObjectSearchSQL : Error : " + ex.Message);
        }
        return strObjectSearchSql;
    }

    public string PagesetQuickSearchSql(DataTable dtaPageSrch, HtmlForm frmObj)
    {
        DataRow[] dr_PageQuickSrch = dtaPageSrch.Select("quick_search=1", "search_seq");
        string strQuickSearchSql = "";
        for (int j = 0; j < dr_PageQuickSrch.Length; j++)
        {
            string strAttribId = dr_PageQuickSrch[j]["search_attrib_id"].ToString();
            string strPageId = dr_PageQuickSrch[j]["page_id"].ToString();
            string strBindRowID = dr_PageQuickSrch[j]["control_bind_id"].ToString();
            string strQuickSearchValue = null;

            // Commented by srivatsan
            DropDownList ddl = (DropDownList)frmObj.FindControl("ctl00$ContentPlaceHolder3$Quick_Search_" + strPageId + "_" + strAttribId);
            //if (frmObj.Page.Request.Form["ctl00$ContentPlaceHolder3$Quick_Search_" + strPageId + "_" + strAttribId] != null)
            if (getValueInBothGetandPost(ref frmObj, strPageId , strAttribId) != null)

            //DropDownList ddl = (DropDownList)frmObj.FindControl("ctl00_ContentPlaceHolder3_Quick_Search_" + strPageId + "_" + strAttribId);
            //if (frmObj.Page.Request.Form["ctl00_ContentPlaceHolder3_Quick_Search_" + strPageId + "_" + strAttribId] != null)
            {
                //strQuickSearchValue = frmObj.Page.Request.Form["ctl00$ContentPlaceHolder3$Quick_Search_" + strPageId + "_" + strAttribId].ToString();
                strQuickSearchValue = getValueInBothGetandPost(ref frmObj, strPageId, strAttribId).ToString();
                //strQuickSearchValue = frmObj.Page.Request.Form["ctl00_ContentPlaceHolder3_Quick_Search_" + strPageId + "_" + strAttribId].ToString();
                string sBindStoreField = "";
                string sValues = "";
                if (strBindRowID != "") //implemented by Prithi on 11-Nov-2008
                {
                    DataRow drBind = HDD.GetTableRow("select * from sy_bnd where af_row_id = '" + strBindRowID + "';");
                    string sBindDisplayField = "", sBindTable = "";

                    if (drBind != null)
                    {
                        sBindStoreField = drBind["bind_value"].ToString();
                        sBindDisplayField = drBind["bind_text"].ToString();
                        sBindTable = drBind["bind_table"].ToString();

                        //DataTable dtBind = HDD.GetDataTable("select " + sBindStoreField + " from " + sBindTable + " where " + sBindDisplayField + "='" + strQuickSearchValue.Replace("'", "''") + "'"); // Modified by srivatsan on June 04 2009

                        //foreach (DataRow dr in dtBind.Rows)
                          //  sValues = sValues + "'" + dr[sBindStoreField].ToString() + "',";
                        //sValues = sValues.TrimEnd(',');
                    }

                    if (ddl.Items.FindByValue(strQuickSearchValue) == null)//To check for values
                    {
                        strQuickSearchValue = null;
                        ddl.SelectedValue = GlobalValues.ShowAll;
                    }
                }
                else
                {
                    if (ddl.Items.FindByText(strQuickSearchValue) == null)
                    {
                        strQuickSearchValue = null;
                        ddl.SelectedValue = GlobalValues.ShowAll;
                    }
                }

                //if (dr_PageQuickSrch[j]["control_attrib_type"].ToString().ToLower() == "dt")
                //    strQuickSearchValue = DDI.getGMT(strQuickSearchValue, sUTC_Offset);

                if (strQuickSearchValue == null)
                {
                    strQuickSearchValue = "";
                }

                #region Old code commented by 'Imran Gani' on 28-Feb-2014, to avoid 'if' statement and to use switch case
                //if (dr_PageQuickSrch[j]["control_attrib_type"].ToString().ToLower() == "dt" && strQuickSearchValue != "" && strQuickSearchValue != "--All--")
                //{
                //    Localization li = new Localization();
                //    strQuickSearchValue = li.getDateTime4TimeZone(strQuickSearchValue, sUTC_Offset, true, false);// .getInvariantDateTime(strQuickSearchValue);
                //    li = null;
                //    //strQuickSearchValue = DDI.getGMT(strQuickSearchValue, sUTC_Offset);
                //}
                //else if (dr_PageQuickSrch[j]["control_attrib_type"].ToString().ToLower() == "cu" && strQuickSearchValue != "" && strQuickSearchValue != "--All--")
                //    strQuickSearchValue = changeCurrencyToDBValue(strQuickSearchValue, currencyCode_Rate);
                //else if (dr_PageQuickSrch[j]["control_attrib_type"].ToString().ToLower() == "da" && strQuickSearchValue != "" && strQuickSearchValue != "--All--")
                //{
                //    Localization li1 = new Localization();
                //    strQuickSearchValue = li1.getInvariantDate(strQuickSearchValue);
                //    li1 = null;
                //}
                #endregion

                #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
                if (strQuickSearchValue != "" && strQuickSearchValue != "--All--")
                {
                    switch (dr_PageQuickSrch[j]["control_attrib_type"].ToString().ToLower())
                    {
                        case "dt":
                            Localization ll = new Localization();
                            strQuickSearchValue = ll.getDateTime4TimeZone(strQuickSearchValue, sUTC_Offset, true, false);
                            ll = null;
                            break;
                        case "da":
                            strQuickSearchValue = MBLocalization.getDateValue(HttpContext.Current.Session["userlocale"].ToString(), strQuickSearchValue);
                            break;
                        case "cu":
                            strQuickSearchValue = changeCurrencyToDBValue(strQuickSearchValue, currencyCode_Rate);
                            break;
                        case "dc":
                        case "nu":
                        case "an":
                            strQuickSearchValue = MBLocalization.getNumericValue(HttpContext.Current.Session["userlocale"].ToString(), strQuickSearchValue).ToString();
                            break;
                    }
                }
                #endregion

                if (strQuickSearchValue != null && strQuickSearchValue != "" && strQuickSearchValue != GlobalValues.ShowAll)
                {
                    //if (sBindStoreField.ToLower() == "af_row_id") // Commented by srivatsan
                    //if (sValues != "")                  
                    //    strQuickSearchSql += " and [" + strPageId + "].[" + strAttribId + "] in (" + sValues + ")";
                    //else
                    //  strQuickSearchSql += " and 1=2 ";
                    //else
                    // Added by srivatsan on June 15 2009 for owner id field
                    if (strAttribId.ToLower() == "created_by" || strAttribId.ToLower() == "modified_by" || strAttribId.ToLower() == "owner_id")
                    {
                        string sUserDisplayName = getUserDisplayName();
                        strQuickSearchSql += " and [" + strPageId + "].[" + strAttribId + "]='" + HDD.GetColumnValue("select af_row_id from sy_usr where " + sUserDisplayName + "='" + strQuickSearchValue + "'") + "'";
                    }
                    else
                        strQuickSearchSql += " and [" + strPageId + "].[" + strAttribId + "]='" + strQuickSearchValue.Replace("'", "''") + "'";
                }

                if (strQuickSearchValue == "")
                {
                    strQuickSearchSql += " and [" + strPageId + "].[" + strAttribId + "] is null";
                }
            }
        }

        return strQuickSearchSql;
    }
    private string getValueInBothGetandPost(ref HtmlForm hf, string pageId, string attribId)
    {
        string ret = null;
        if (hf.Page.Request.Form["ctl00$ContentPlaceHolder3$Quick_Search_" + pageId + "_" + attribId] != null)
            ret = hf.Page.Request.Form["ctl00$ContentPlaceHolder3$Quick_Search_" + pageId + "_" + attribId].ToString();
        else if (hf.Page.Request.QueryString[pageId + "_" + attribId] != null)
            ret = hf.Page.Request.QueryString[pageId + "_" + attribId].ToString();
        return ret;
    }
    private string changeCurrencyToDBValue(string originalValue, ArrayList currencyCode)
    {
        if (currencyCode.Count < 1)
            return originalValue;
        if (currencyCode.Count < 2)
        {
            LogWriter.WriteLog("No Corporate currency defined.");
            return originalValue;
        }
        string ret = originalValue;
        Double inputValue = 0;
        double conversionRate = 0;
        double temp = 0;
        double corporate = 0;
        corporate = double.Parse(currencyCode[2].ToString());
        try
        {
            originalValue = originalValue.Replace(currencyCode[1] + " ", "");
            //inputValue = originalValue == "" ? 0 : double.Parse(originalValue);
            inputValue = originalValue == "" ? 0 : double.Parse(MBLocalization.getNumericValue(HttpContext.Current.Session["userlocale"].ToString(), originalValue).ToString());
            conversionRate = currencyCode[0].ToString() == "" ? 1 : double.Parse(currencyCode[0].ToString());
            temp = (inputValue * conversionRate) / corporate;
            ret = temp.ToString("#0.0000");
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("changeCurrencyToDBValue : Error : " + e.Message);
        }
        return ret;
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        string strPagesetRowId = HttpContext.Current.Request.QueryString["pgs_id"].ToString();
        strPagesetRowId = btn.Attributes["Pageset"];

        string strMenuRowId = HttpContext.Current.Request.QueryString["mn"].ToString();
        string sEditPage = "DynamicScreen.aspx";
        HDDatabase HDD = new HDDatabase();
        GenerateGrid objGD = new GenerateGrid();
        sEditPage = objGD.getEditPage(HDD, strMenuRowId);
        //HttpContext.Current.Session["PK"] = HttpContext.Current.Request.QueryString["PK"].ToString();
        string strPageUrl = sEditPage + "?pgs_id=" + strPagesetRowId + "&mn=" + strMenuRowId;
        strPageUrl = addMasterPrimaryKey(strPageUrl);
        HttpContext.Current.Response.Redirect(strPageUrl);
    }

    private Literal GetPageIcons(string strPagesetRowID) // Added by srivatsan for Icon Display in child Grids
    {
        Literal iconlit = new Literal();
        PageIcons icons = new PageIcons();
        try
        {

            string iconpath = icons.geticonsfrompageset(strPagesetRowID.Replace("'", "''"), 2);


            iconlit.Text = "&nbsp;<img src = " + iconpath + " style='vertical-align:middle;'></img>&nbsp;";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error GetPageIcons:" + ex.Message);
            iconlit.Text = "&nbsp;<img src = " + PageIcons.strdefaulticon.ToString() + "></img>&nbsp; ";
        }
        finally
        {
            icons = null;
        }
        return iconlit;


    }

    public void showadditionalsections(string strPagesetRowId, ref HtmlForm frmObj, DataSet dsePageObj) // Added by srivatsan for next step and related info
    {
        // Added by srivatsan on Jan 28 2009 for Next Step and Related Info


        AdditionalPageInfo addinfo = new AdditionalPageInfo(strPagesetRowId, dsePageObj);
        try
        {
            HtmlTable tableparam = (HtmlTable)DDI.FindControl(frmObj.Controls, "table1");
            //addinfo.addtablerow(ref tableparam, "tdpagesteps", strPagesetRowId, 1, 1,false); //Next Step // Commanded by 'Imran Gani' on 30-Aug-12, to avoid next step at the bottom of the page.
            //addinfo.addtablerow(ref tableparam, "tdrelatedinfo", strPagesetRowId, 2, 1,false); //related info // Commanded by 'Imran Gani' on 15-Aug-12, to avoid related info at the bottom of the page.



            //Added by srivatsan for next step and related info in page header
            if (dsePageObj != null)
            {
                if (dsePageObj.Tables["Page"] != null)
                {

                    if (dsePageObj.Tables["Page"].Rows[0]["is_next_step_enabled"].ToString().Trim() != "" ? Convert.ToBoolean(dsePageObj.Tables["Page"].Rows[0]["is_next_step_enabled"].ToString().Trim()) : false)
                    {
                        HtmlTable htnextstep = new HtmlTable();
                        //htnextstep.Width = "100%"; // Commanded by 'Imran Gani' on 24-Oct-13, to control the width in all browsers - especially chrome.
                        htnextstep.CellSpacing = 0;
                        htnextstep.CellPadding = 0;
                        htnextstep.Border = 0;
                        HtmlTableRow htrnextstep = new HtmlTableRow();
                        HtmlTableCell htcnextstep = new HtmlTableCell();
                        htcnextstep.Width = "100%";
                        htcnextstep.NoWrap = true;

                        addinfo.addtablerow(ref htnextstep, "tdnextstep_header", strPagesetRowId, 1, 1,true);
                        NextStepinPageHeader(frmObj, htnextstep);
                    }

                    if (dsePageObj.Tables["Page"].Rows[0]["is_rel_info_enabled"].ToString().Trim() != "" ? Convert.ToBoolean(dsePageObj.Tables["Page"].Rows[0]["is_rel_info_enabled"].ToString().Trim()) : false)
                    {
                        HtmlTable htrelinfo = new HtmlTable();
                        //htrelinfo.Width = "100%"; // Commanded by 'Imran Gani' on 24-Oct-13, to control the width in all browsers - especially chrome.
                        htrelinfo.CellSpacing = 0;
                        htrelinfo.CellPadding = 0;
                        htrelinfo.Border = 0;
                        HtmlTableRow htrrelinfo = new HtmlTableRow();
                        HtmlTableCell htcrelinfo = new HtmlTableCell();
                        htcrelinfo.Width = "100%";
                        htcrelinfo.NoWrap = true;
                        addinfo.addtablerow(ref htrelinfo, "tdrelinfo_header", strPagesetRowId, 2, 1,true);
                        RelatedInfoinPageHeader(frmObj, htrelinfo);
                    }
                    


                    //string testdata = tableparam.InnerHtml;

                    
                    
                }

            }




        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error showadditionalicons :" + ex.Message);
        }
        finally
        {
            addinfo = null;
        }
        //
    }



    private void NextStepinPageHeader(HtmlForm frmObj, HtmlTable ht)
    {
        if (frmObj != null)
        {
            if (ht.Rows.Count > 0)
            {
                if (frmObj.FindControl("ctl00$lbl_appmaster_nextstep") != null)
                {
                    Label lblObj = (Label)frmObj.FindControl("ctl00$lbl_appmaster_nextstep");
                    lblObj.Visible = true;

                    if (frmObj.FindControl("ctl00$div_nextstep") != null)
                    {
                        Control con = (Control)frmObj.FindControl("ctl00$div_nextstep");
                        HtmlGenericControl gencontrol = (HtmlGenericControl)con;
                        if (ht.Rows.Count > 0)
                        {
                            int rowcount = ht.Rows.Count;

                            ht.Rows.RemoveAt(rowcount - 1);

                        }

                        gencontrol.Controls.Add(ht);
                    }

                }
            }
        }
    }

    private void RelatedInfoinPageHeader(HtmlForm frmObj, HtmlTable ht)
    {
        if (frmObj != null)
        {
            if (ht.Rows.Count > 0)
            {
                if (frmObj.FindControl("ctl00$lbl_appmaster_relatedinfo") != null)
                {
                    Label lblObj = (Label)frmObj.FindControl("ctl00$lbl_appmaster_relatedinfo");
                    lblObj.Visible = true;

                    if (frmObj.FindControl("ctl00$div_related") != null)
                    {
                        Control con = (Control)frmObj.FindControl("ctl00$div_related");
                        HtmlGenericControl gencontrol = (HtmlGenericControl)con;

                        if (ht.Rows.Count > 0)
                        {
                            int rowcount = ht.Rows.Count;

                            ht.Rows.RemoveAt(rowcount - 1);

                        }

                        gencontrol.Controls.Add(ht);
                    }
                }
            }
        }
    }




    private string getAddNewLink(HtmlInputButton button)
    {
        //Button btn = (Button)button;
        HtmlInputButton btn = (HtmlInputButton)button;
        string strPagesetRowId = HttpContext.Current.Request.QueryString["pgs_id"].ToString();
        strPagesetRowId = btn.Attributes["Pageset"];

        string strMenuRowId = HttpContext.Current.Request.QueryString["mn"].ToString();
        string sEditPage = "DynamicScreen.aspx";
        HDDatabase HDD = new HDDatabase();
        GenerateGrid objGD = new GenerateGrid();
        /********* Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts *********/
        if (strPagesetRowId == "aa922f981c2500e0") // Pageset_id = 'task_config'
            strMenuRowId = HDD.GetColumnValue("select af_row_id from sy_mnu where pageset_id='" + strPagesetRowId + "'");
        /********* End of Task & Alerts *********/
        sEditPage = objGD.getEditPage(HDD, strMenuRowId);
        //HttpContext.Current.Session["PK"] = HttpContext.Current.Request.QueryString["PK"].ToString();
        string strPageUrl = sEditPage + "?pgs_id=" + strPagesetRowId + "&mn=" + strMenuRowId;
        strPageUrl = addMasterPrimaryKey(strPageUrl);
        //HttpContext.Current.Response.Redirect(strPageUrl);

        return strPageUrl;
    }

    private string getDistinct(DataTable dt, string field) // Get distinct values from the datatable for the field as string
    {
        StringBuilder sb = new StringBuilder();
        string result = "";
        try
        {
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr[field].ToString() != "")
                    {
                        if (!sb.ToString().Contains("'" + dr[field].ToString() + "'"))
                        {
                            sb.Append("'" + dr[field].ToString() + "',");
                        }
                    }
                }
                if (sb.ToString() != "")
                {
                    result = sb.ToString().Substring(0, sb.Length - 1);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetDistinctRecords :" + ex.Message);
        }
        return result;

    }

    // This will create a temp column for bind with string datatype and remove existing column.
    // Used for displaying bind fields in list page
    private DataSet addBindColumn(DataSet ds, string bindcolumn)  // Added by srivatsan on July 16 2009
    {
        int ordinalposition = 0;
        if (ds != null)
        {
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Columns.Contains(bindcolumn))
                    {
                        ds.Tables[0].Columns.Add(bindcolumn + "_temp");

                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            ds.Tables[0].Rows[i][bindcolumn + "_temp"] = ds.Tables[0].Rows[i][bindcolumn];
                        }

                        ordinalposition = ds.Tables[0].Columns[bindcolumn].Ordinal;
                        ds.Tables[0].Columns.Remove(bindcolumn);

                        // foreach (DataColumn dc in ds.Tables[0].Columns)
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                        {
                            if (ds.Tables[0].Columns[j].Caption == bindcolumn + "_temp")
                            {
                                ds.Tables[0].Columns[j].Caption = bindcolumn;
                                ds.Tables[0].Columns[j].ColumnName = bindcolumn;
                                ds.Tables[0].Columns[j].SetOrdinal(ordinalposition);

                                ds.AcceptChanges();

                            }

                        }

                    }


                }
            }
        }
        return ds;
    }

    //Added by srivatsan on July 27 2009 
    //This will add Go Button to the PlaceHolder for filters
    private void AddGoButton(ref PlaceHolder ph_QS, DataTable pdtaPageSrch)
    {
        Button btnGO = new Button();
        btnGO.ID = "btngo";
        btnGO.Text = " Go ";
        try
        {
            //dtaPageSrch = pdtaPageSrch;
            //ph_QS.Controls.Add(new LiteralControl("<tr>"));
            //ph_QS.Controls.Add(new LiteralControl("<td align=right width=20%>"));
            //ph_QS.Controls.Add(new LiteralControl("</td>"));
            //ph_QS.Controls.Add(new LiteralControl("<td align=left width=80%>"));
            //ph_QS.Controls.Add(new LiteralControl("<td>"));
            btnGO.Click += new EventHandler(btnGO_Click);
            btnGO.OnClientClick = "javascript:return SetFirstPage();";
            btnGO.CssClass = "controlFont";
            btnGO.Style.Add("vertical-align", "bottom");
            //btnGO.Style.Add("height", "19px");
            btnGO.Style.Add("width", "60px");
            ph_QS.Controls.Add(new LiteralControl("&nbsp;"));
            ph_QS.Controls.Add(btnGO);
            //ph_QS.Controls.Add(new LiteralControl("</td>"));
            //ph_QS.Controls.Add(new LiteralControl("</tr>"));
        }
        catch
        {
        }
    }



    protected void btnGO_Click(object sender, EventArgs e)
    {
        //GenerateGrid objGG = new GenerateGrid();
        //PageInfoLoad PIL = new PageInfoLoad();
        //try
        //{
        //    Button btn = (Button)sender;
        //    if (btn.Page.IsPostBack)
        //    {
        //        //DataSet dsePageObj = PIL.GetPageSetPagesSrchInfo(HttpContext.Current.Request.QueryString["pgs_id"].ToString());
        //        //DataTable dtaPage = dsePageObj.Tables["Page"];
        //        //DataTable dtaPageSrch = dsePageObj.Tables["PageSrch"];
        //        //objGG.BuildQuickSearch(dtaPage, dtaPageSrch, HttpContext.Current.Request.QueryString["pgs_id"].ToString(), btn.Page.Form); // Commented by srivatsan on July 27 2009
        //    }
        //}
        //catch
        //{

        //}
    }

    // Added by srivatsan on Sep 29 2009 for Notes changes
    // This function will modify the query to fetch the records to be displayed in the List page
    // This will add the related_af_row_id as parameter to the existing query
    private string GetNotesParameter(string strPageSql,DataTable dtaPageSrch)
    {
        try
        {
            if (dtaPageSrch != null)
            {
                if (dtaPageSrch.Rows.Count > 0)
                {
                    if (dtaPageSrch.Rows[0]["pageset_id"].ToString() == "c6e7de1b8b5f0835")
                    {
                        if (HttpContext.Current.Request.QueryString["PK"] != null)
                        {
                            strPageSql += " and related_af_row_id = '" + HttpContext.Current.Request.QueryString["PK"].ToString() + "' ";
                        }
                    }
                }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetNotesParameter : " + ex.Message);
        }

        return strPageSql;
    }

    /********* Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts *********/
    private string GetTaskParameter(string strPageSql, DataTable dtaPageSrch)
    {
        try
        {
            if (dtaPageSrch != null)
            {
                if (dtaPageSrch.Rows.Count > 0)
                {
                    if (dtaPageSrch.Rows[0]["pageset_id"].ToString() == "aa922f981c2500e0")
                    {
                        HDDatabase HDD = new HDDatabase();
                        DataTable dt_task = HDD.GetDataTable("select * from sy_task_object_ref where  obj_record_ref='" + HttpContext.Current.Request.QueryString["PK"].ToString() + "'");
                        if (dt_task.Rows.Count > 0)
                        {
                            strPageSql += " and af_row_id in (";
                            for (int i = 0; i < dt_task.Rows.Count; i++)
                            {
                                strPageSql += "'" + dt_task.Rows[i]["task_row_id"] + "',";
                            }
                            strPageSql = strPageSql.TrimEnd(',');
                            strPageSql += ")";
                        }
                        else
                            strPageSql = "";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetTaskParameter : " + ex.Message);
        }
        finally
        { }
        return strPageSql;
    }
    /********* End of Task & Alerts *********/

    // Added by srivatsan for Action Button.
    // This will check if action button cna be shown
    public bool CanShowActionButton(ref DataRow[] dractions,DataSet dsPageInfo)
    {
        bool status = false;
        /********* Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts *********/
        ScreenReader SR = new ScreenReader();
        HDDatabase HDD = new HDDatabase();
        try
        {
            string str_ObjID = dsPageInfo.Tables["Page"].Rows[0]["object_id"].ToString();
            string associate_task = HDD.GetColumnValue("select associate_task from sy_obj where object_id='" + str_ObjID + "'").ToString();
            if (associate_task.ToLower() == "true")
            {
                string task_name = HDD.GetColumnValue("select mem_name from sy_acr_mem where acr_id ='9cbedf648eaf7f06' and mem_id='name'");
                string strMenuRowId = HDD.GetColumnValue("select af_row_id from sy_mnu where pageset_id='aa922f981c2500e0';"); //pageset_id='task_config'
                DataRow dr_action = dsPageInfo.Tables["Page Actions"].NewRow();
                dr_action["name"] = task_name;
                dr_action["page_id"] = dsPageInfo.Tables["Page"].Rows[0]["af_row_id"].ToString();
                dr_action["description"] = task_name;
                dr_action["target_url"] = "TaskConfig.aspx?pgs_id=aa922f981c2500e0&mn=" + strMenuRowId + "&pg=" + dsPageInfo.Tables["Page"].Rows[0]["af_row_id"].ToString();  //pgs_id='task_config'
                dr_action["active"] = 1;
                dr_action["seq"] = 1;
                dr_action["af_row_id"] = SR.getHashKey();
                dr_action["created_at"] = DateTime.Now.ToUniversalTime();
                dr_action["created_at"] = DateTime.Now.ToUniversalTime();

                dsPageInfo.Tables["Page Actions"].Rows.Add(dr_action);
                dractions = dsPageInfo.Tables["Page Actions"].Select();
                status = true;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Show  Action for Task  :" + ex.Message);
        }
        finally
        {
            HDD = null;
            SR = null;
        }
        /********* End of Task & Alerts *********/
        try
        {
            if (dsPageInfo != null)
            {
                if (dsPageInfo.Tables.Count > 0)
                {
                    if (dsPageInfo.Tables["Page Actions"] != null)
                    {
                        if (dsPageInfo.Tables["Page Actions"].Rows.Count > 0)
                        {
                            dractions = dsPageInfo.Tables["Page Actions"].Select();
                            status = true;
                        }
                    }
                }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : CanShowActionButton : "+ ex.Message);
        }
        return status;
    }

    private int GetRowCount(DataSet ds)
    {
        int result = 0;
        try
        {
            if(ds!=null)
                if(ds.Tables.Count>0)
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        result = ds.Tables[0].Rows.Count;
                    }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetRowCount :"+ex.Message);
        }
        return result;
    }

    /// <summary>
    /// This function will return true if MaxBlox Email Compose page can be used
    /// </summary>
    /// <returns></returns>
    private bool UseMaxBloxEmailCompose()//srivatsan
    {
        bool status = false;
        HDDatabase hdd = null;
        try
        {
            hdd = new HDDatabase();
            string sql = "select mem_value1 from sy_acr_mem where af_row_id = '62b95ed0102fc1cb'";
            string result = hdd.GetColumnValue(sql);
            status = result.Trim() != "" ? Convert.ToBoolean(result) : false;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : UseMaxBloxEmailCompose :" + ex.Message);
        }
        finally
        {
            hdd = null;
        }
        return status;
    }
    // Added by 'Imran Gani' on Sep 18 2012 for Documents changes
    /// <summary>
    /// This function will modify the query to fetch the Document records to be displayed in the List page
    /// </summary>
    /// <param name="strPageSql"></param>
    /// <param name="dtaPageSrch"></param>
    /// <returns>This will add the related_af_row_id as parameter to the existing query</returns>
    private string GetDocumentsParameter(string strPageSql, DataTable dtaPageSrch)
    {
        try
        {
            if (dtaPageSrch != null)
            {
                if (dtaPageSrch.Rows.Count > 0)
                {
                    if (dtaPageSrch.Rows[0]["pageset_id"].ToString() == "5f4649e689509dea")
                    {
                        if (HttpContext.Current.Request.QueryString["PK"] != null)
                        {
                            strPageSql += " and related_af_row_id = '" + HttpContext.Current.Request.QueryString["PK"].ToString() + "' ";
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetDocumentsParameter : " + ex.Message);
        }
        return strPageSql;
    }

    // Added by 'Imran Gani' on Sep 18 2012 for Documents changes
    /// <summary>
    /// To add a link on Add New button in Document list.
    /// </summary>
    /// <param name="button"></param>
    /// <returns>URL</returns>
    private string getLinkForDocument(HtmlInputButton button)
    {
        try
        {
            HtmlInputButton btn = (HtmlInputButton)button;
            string strPagesetRowId = HttpContext.Current.Request.QueryString["pgs_id"].ToString();
            strPagesetRowId = btn.Attributes["Pageset"];

            string strMenuRowId = HttpContext.Current.Request.QueryString["mn"].ToString();
            string sEditPage = "Documents.aspx";

            string strPageUrl = sEditPage + "?pgs_id=" + strPagesetRowId + "&mn=" + strMenuRowId;
            strPageUrl = addMasterPrimaryKey(strPageUrl);
            return strPageUrl;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getLinkForDocument : " + ex.Message);
            return "";
        }
    }

    /// <summary>
    /// To handle the datatype for each control of a page.
    /// </summary>
    /// <param name="strPagesetRowId">Page set ID</param>
    /// <param name="dtData">Displaying record DataTable with all column in string type</param>
    /// <param name="hsDatatype">Datatype details of a page</param>
    /// <param name="dsPageInfo">Page dictionary information</param>
    // Implemented by 'Imran Gani' on 22-Apr-2013, to handle the datatype of a page controls.
    public void HandleControlDataType(string strPagesetRowId, DataTable dtData, Hashtable hsDatatype, DataSet dsPageInfo)
    {
        Localization ll = new Localization();
        try
        {
            if (currencyCode_Rate.Count == 0)
                loadCurrencySettings();
            if (sUTC_Offset == "")
                sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
            string strText = "";
            for (int i = 0; i < dtData.Rows.Count; i++)
            {
                for (int j = 0; j < dtData.Columns.Count; j++)
                {
                    strText = "";
                    if (strPagesetRowId == "5f4649e689509dea" && dtData.Columns[j].ColumnName.ToLower() == "file name")
                        strText = dtData.Rows[i][j].ToString();
                    else
                        strText = HttpUtility.HtmlEncode(dtData.Rows[i][j].ToString());

                    if (strText != "")
                    {
                        if (hsDatatype.Contains(dtData.Columns[j].ColumnName))
                        {
                            dtData.Columns[j].DataType = System.Type.GetType("System.String");
                            switch (hsDatatype[dtData.Columns[j].ColumnName].ToString().ToLower())
                            {
                                case "da":
                                    strText = MBLocalization.getLocalizedDate(HttpContext.Current.Session["userlocale"].ToString(), DateTime.Parse(strText));
                                    break;
                                case "dt":
                                    strText = ll.getDateTime4TimeZone(strText, sUTC_Offset, false, false);
                                    break;
                                case "cu":
                                    strText = DDI.manageCurrency(strText, currencyCode_Rate);
                                    break;
                                case "nu":
                                case "an":
                                    strText = MBLocalization.getLocalizedInteger(HttpContext.Current.Session["userlocale"].ToString(), int.Parse(strText));
                                    break;
                                case "dc":
                                case "fl":
                                    strText = MBLocalization.getLocalizedDecimal(HttpContext.Current.Session["userlocale"].ToString(), double.Parse(strText));
                                    break;
                                default:
                                    break;
                            }
                        }
                        handleControlType(ref strText, ref dsPageInfo, ref dtData, j, i);
                        dtData.Rows[i][j] = strText;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : HandleControlDataType : " + ex.Message);
        }
    }
}
